* Analysis on ADM1 Level

/*
packages to install
ssc install reghdfe
ssc install ivreghdfe
ssc install ftools
ssc install ivreg2
ssc install ranktest
ssc install tuples
ssc install xtpqml
ssc install erepost
net install st0549 // boottest
ssc install boottest, replace
net install st0085_2 	// esttab
net install dm88_1 	// renvars
net install sg97_5  // frmttable
net install gr0059_1	// coefplot 
ssc install outreg2	
*/





*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
********************
* DATA PREPARATION *
********************
*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all
set maxvar 32767
use "$data\Merge\IDA_Aid_GED_ADM1.dta", clear

* keep only African dataset
keep if unregion2=="Africa"

// drop small economies and islands
drop if d_smallcountry ==1

* Generate continental identifiers
egen continent_num=group(unregion2)

* Generate an identifier for countries with small variation in ethnic power group stati (subsequently, we exclude these countries for regressions on ethnic power groups)
gen epr_low_var=0
replace epr_low_var=1 if ISO3=="TUN" | ISO3=="SWZ" | ISO3=="SOM" | ISO3=="MUS" | ISO3=="MDG" | ISO3=="LSO" | ISO3=="GMB" | ISO3=="ESH" | ISO3=="DJI" | ISO3=="BDI" | ISO3=="BFA" 

* Generate Trend Variables:
sort ID_adm1_num transaction_year
bysort ID_adm1_num: egen mean_temp=mean(temp)
egen trend=group(transaction_year)
gen trend_sq=trend*trend
gen trend_cub=trend*trend*trend


* Aid data
gen lnaid=ln(WBAID_ADM1_LOC+0.01)
label var lnaid  "Log of location weighted World Bank Aid per capita +0.01"
gen lnaid_c=ln(CAID_ADM1_LOC+0.01)
label var lnaid_c  "Log of location weighted Chinese Aid per capita +0.01"

gen lnaid_pop=ln(WBAID_ADM1_POP+0.01)
label var lnaid_pop  "Log of population weighted World Bank Aid per capita +0.01"
gen lnaid_pop_c=ln(CAID_ADM1_POP+0.01)
label var lnaid_pop_c  "Log of population weighted Chinese Aid per capita +0.01"


* Conflict Data
* Rename SCAD variables for consistency with other labeling
renvars D_pro_gov_violence D_pro_gov_vio_leth D_pro_gov_vio_nleth D_demo D_riot D_strike D_total_violence D_total_rds / D_pro_gov_v_adm1 D_pro_gov_v_l_adm1 D_pro_gov_v_nl_adm1 D_demo_adm1 D_riot_adm1 D_strike_adm1 D_tot_v_adm1 D_tot_rds_adm1
* Rescale Dummies for easier interpretation
foreach var in D_pro_gov_v_adm1 D_pro_gov_v_l_adm1 D_pro_gov_v_nl_adm1 D_demo_adm1 D_riot_adm1 D_strike_adm1 D_tot_v_adm1 D_tot_rds_adm1 D_repress_all D_repress_nl D_repress_l {
	replace `var'=`var'*100
}
gen lnbrd_adm1=ln(brd_adm1+0.01)
* Genreate new intensity thresholds
gen inten1_adm1=0
replace inten1_adm1=100 if brd_adm1>=5

gen inten2_adm1=0
replace inten2_adm1=100 if brd_adm1>=25


* Generate Latitude and Longitude for time-interaction
gen lon=abs(xcoord)
gen lat=abs(ycoord)

*** Prepare Rolling IV - WB Aid***
*2 Years
xtset ID_adm1_num transaction_year
gen received=0
replace received=1 if WBAID_ADM1_LOC!=0 & WBAID_ADM1_LOC!=. 
gen eligible=1
sort ID_adm1_num transaction_year
bysort ID_adm1_num: gen eligible_sum=sum(eligible)
bysort ID_adm1_num: gen received_sum=sum(received)
bysort ID_adm1_num: egen eligible_tot=total(eligible)
bysort ID_adm1_num: egen received_tot=total(received)
gen prob_cum=received_sum/eligible_sum
gen prob_cons=received_tot/eligible_tot
gen prob_rolling2=(l1.received+l0.received)/2 if transaction_year>=1996
gen prob_rolling3=(l2.received+l1.received+l0.received)/3 if transaction_year>=1997
gen prob_rolling4=(l3.received+l2.received+l1.received+l0.received)/4 if transaction_year>=1998
drop eligible* received*




*** Prepare IV - disbursement count**
gen received=0
replace received=1 if WBAID_disbcount_ADM1_LOC!=0 & WBAID_disbcount_ADM1_LOC!=. 
gen eligible=1
sort ID_adm1_num transaction_year
bysort ID_adm1_num: gen eligible_sum=sum(eligible)
bysort ID_adm1_num: gen received_sum=sum(received)
bysort ID_adm1_num: egen eligible_tot=total(eligible)
bysort ID_adm1_num: egen received_tot=total(received)
gen prob_cum_count=received_sum/eligible_sum
drop eligible* received*



*** Prepare Rolling IV - Chinese Aid***
xtset ID_adm1_num transaction_year
*2 Years
gen received=0
replace received=1 if CAID_ADM1_LOC!=0 & CAID_ADM1_LOC!=. & transaction_year>=2000 & transaction_year<=2012
gen eligible=1 if transaction_year>=2000 & transaction_year<=2012
sort ID_adm1_num transaction_year
bysort ID_adm1_num: gen eligible_sum=sum(eligible) if transaction_year>=2000 & transaction_year<=2012
bysort ID_adm1_num: gen received_sum=sum(received) if transaction_year>=2000 & transaction_year<=2012
bysort ID_adm1_num: egen eligible_tot=total(eligible) if transaction_year>=2000 & transaction_year<=2012
bysort ID_adm1_num: egen received_tot=total(received) if transaction_year>=2000 & transaction_year<=2012
gen prob_cum_c=received_sum/eligible_sum if transaction_year>=2000 & transaction_year<=2012
gen prob_cons_c=received_tot/eligible_tot if transaction_year>=2000 & transaction_year<=2012
gen prob_rolling_c2=(l1.received+l0.received)/2 if transaction_year>=2001
gen prob_rolling_c3=(l2.received+l1.received+l0.received)/3 if transaction_year>=2002
gen prob_rolling_c4=(l3.received+l2.received+l1.received+l0.received)/4 if transaction_year>=2003
drop eligible* received*


* Prepare IBRD variable
gen temp_IBRD = IBRD_ADM1_LOC
replace temp_IBRD=0 if IBRD_ADM1_LOC<=0
gen ln_IBRD_ADM1_LOC=ln(temp_IBRD+0.01)
drop temp_IBRD


* Create IDA_position fluctuation cleaned from general trends
reg IDA_position trend
predict IDA_position_cleaned, resid


* Create running average of IDA position (e.g., for aid in t IDA_position in t determines the first half of the transaction_year and aid in t+1 determines the second half of the transaction_year)
sort ID_adm1_num transaction_year
gen IDA_position_run=(IDA_position+f1.IDA_position)/2
* For out of sample values refer to IDA_IBRD values from Brad Parks (see Data/Aid/IDA_IBRD_Liquidity.xlsx)
*replace IDA_position_run=(0.788+0.807)/2 if transaction_year==2012
replace IDA_position_run=(1.106+0.981)/2 if transaction_year==1995



* Detrend IDA Position
capture gen constant=1
reg IDA_position_run trend constant, nocons
gen IDA_position_run_detrend = IDA_position_run-_b[trend]*trend-_b[constant]


* Set Chinese aid to missing for non-African states and year<2000 & years>2012
replace lnaid_c=. if unregion2!="Africa" | transaction_year<2000 | transaction_year>2012


* Prepare first difference analysis
gen d1lnaid=d1.lnaid
gen d1lnaid_c=d1.lnaid_c
gen d1IDA_position_run=d1.IDA_position_run
gen d1factor1=d1.factor1


* Create Indicator for only one group
gen one_group=0
replace one_group=1 if ngroup_adm1_10km==1
* Power Status Indicators:
gen share_powerfull=(st_DOMINANT +st_JUNIORPARTNER +st_MONOPOLY+  st_SENIORPARTNER)/ngroup_adm1_10km
gen share_powerless=(st_DISCRIMINATED +st_POWERLESS_IRRELEVANT +st_SELFEXCLUSION)/ngroup_adm1_10km
gen share_discriminated=st_DISCRIMINATED/ngroup_adm1_10km
gen share_selfexcluded=st_SELFEXCLUSION/ngroup_adm1_10km


* Create region if groups is exclusively populated by coalition groups or not:
gen group_coalition=.
replace group_coalition=0 if (st_DISCRIMINATED!=0 | st_POWERLESS_IRRELEVANT!=0 | st_SELFEXCLUSION!=0 | st_STATECOLLAPSE!=0 ) & !missing(st_DISCRIMINATED, st_POWERLESS_IRRELEVANT, st_SELFEXCLUSION, st_DOMINANT, st_MONOPOLY, st_SENIORPARTNER, st_JUNIORPARTNER)
replace group_coalition=1 if (st_DISCRIMINATED==0 & st_POWERLESS_IRRELEVANT==0 & st_SELFEXCLUSION==0 & st_STATECOLLAPSE==0 )  & !missing(st_DISCRIMINATED, st_POWERLESS_IRRELEVANT, st_SELFEXCLUSION, st_DOMINANT, st_MONOPOLY, st_SENIORPARTNER, st_JUNIORPARTNER)
label var group_coalition "Categorical variable: (0) At least one group powerless; (1) All powerfull"

* Generate identifiers for clusters
egen fcy=group(state transaction_year)
egen fc=group(state)
egen fr=group(ID_adm1_num)


* Labeling
label var lnbrd_adm1  "log of Battle-related deaths + 0.01"
label var ln_IBRD_ADM1_LOC "log of location weighted IBRD funding"
label var inten1_adm1 "dichotomous indicator (0/100) for for 5>=battle deaths"
label var inten2_adm1 "dichotomous indicator (0/100) for for 25>=battle deaths "
label var lon "Longitude"
label var lat "Latitude"
label var prob_cum "IDA: Cumulative/time variant probability"
label var prob_rolling2 "IDA: Cumulative/time variant probability for current + 1 previous year"
label var prob_rolling3 "IDA: Cumulative/time variant probability for current + 2 previous years"
label var prob_rolling4 "IDA: Cumulative/time variant probability for current + 3 previous years"
label var prob_cons "IDA: Constant/non-time variant probability"
label var prob_cum_c "China: Cumulative/time variant probability"
label var prob_cons_c "China: Constant/non-time variant probability"
label var prob_rolling_c2 "China: Cumulative/time variant probability for current + 1 previous year"
label var prob_rolling_c3 "China: Cumulative/time variant probability for current + 2 previous years"
label var prob_rolling_c4 "China: Cumulative/time variant probability for current + 3 previous years"
label var IDA_position_run "Two year moving average of IDA position to account for fiscal year"
label var IDA_position_run_detrend "IDA_position_run without linear trend"
label var d1IDA_position_run "first difference of IDA_position_run"
label var d1factor1 "first difference of factor1"
label var d1lnaid "first difference of lnaid"
label var d1lnaid_c  "first difference of lnaid_c"
label var one_group "Dummy (0/1) if region is populated by only one ethnic group"
label var share_powerfull "Numerical share of groups which are part of national power sharing agreement (EPR)"
label var share_powerless "Numerical share of groups which are not part of national power sharing agreement (EPR)"
label var share_discriminated  "Numerical share of groups which are discriminated at national level (EPR)"
label var share_selfexcluded "Numerical share of groups which self exlcude from power at national level (EPR)"
label var prob_cum_count "IDA Probject count: Cumulative/time variant probability"
label var epr_low_var "Dummy for countries with low variation in ethnic power group stati (EPR)"
label var trend_sq "Quadratic trend"
label var trend_cub "Cubic trend"
label var mean_temp "Constant/non-time variant regional temperature"


***************
* Globals for *
* Regressions *
***************
xtset ID_adm1_num transaction_year
* All controls
global control1 droughtend_spi droughtstart_spi temp prec_gpcc 
global control2 droughtend_spi droughtstart_spi temp prec_gpcc c.ttime_mean#i.transaction_year  c.landarea#i.transaction_year  c.dist_capital#i.transaction_year c.mean_temp#i.transaction_year c.elevation_std#i.transaction_year c.Dborder#i.transaction_year c.Driver#i.transaction_year c.Dlake#i.transaction_year c.Docean#i.transaction_year c.lat#i.transaction_year c.lon#i.transaction_year
global control3 L2.drug_y L2.gem_y  L2.isum_pop_ADM1 L2.goldsurface_y L2.diamprim_y L2.diamsec_y L2.petroleum_y L2.excluded  L2.ln_IBRD_ADM1_LOC L2.lights_sum

*Labeling
global ln "$\ln" 

xtset ID_adm1_num transaction_year
save "$data\working_file.dta",replace



********************************************
* Descriptive Figures on   Location Counts *
********************************************
use "$data/aid_by_precision_code.dta", clear

* Shares of Locations by precision
foreach a in 12 3 4 5678{
gen share`a'=total`a'/total
}
* Shares of Disbursements by precision
foreach a in 12 3 4 5678{
gen share_aid`a'=total_aid`a'/total_aid
}


* Figure 1: Disbursement/Commitment Shares by Geocoding Precision
graph hbar  share_aid12 share_aid3 share_aid4 share_aid5678, stack over(donor) graphregion( color(white)) scheme(s1mono) lintensity(100) intensity(80) bar(1, color(red*1.5) ) bar(2, color(red*1)) bar(3, color(orange*1))  bar(4, color(orange*0.5))  legend(label(1 "Point Coordinates" ) label(2 "ADM2") label(3 "ADM1" ) label(4 "Less precise than ADM1"))   // title("Disbursement/ Commitment Amounts")
graph export "$graphs/Precision/precision_WB_China_disbursements(cum_percent).png", as(png) replace
graph close


* Figure 7: No. of Project Locations by Precision Codes
graph hbar  share12 share3 share4 share5678, stack over(donor) graphregion( color(white)) scheme(s1mono) bar(1, color(grey*0.65)) bar(2, color(grey*0.5)) bar(3, color(grey*0.25))  bar(4, color(grey*0.1)) legend(label(1 "Point Coordinates" ) label(2 "ADM2") label(3 "ADM1" ) label(4 "Less precise than ADM1")) // title("Number of Project Locations") 
graph export "$graphs/Precision/precision_WB_China(cum_percent).png", as(png) replace
graph close


************************************************************************************************************************************/
********************************************
* Descriptive Statistics - Tables 		   *
********************************************
/************************************************************************************************************************************
*************************************************************************************************************************************
														Create summary statistics
expected statistics: 
Table 1 Donor Comparison – WB vs. China
- Mean, std, min, max of each aid type (log and unlogged)

Table 2


*************************************************************************************************************************************
************************************************************************************************************************************/
* Table 1 - Donor Comparison – WB vs. China
* Save continental identifiers
use "$data\Merge\IDA_Aid_GED_ADM1.dta", clear
 preserve
keep unregion2 ADM0 ID_adm1 d_smallcountry
duplicates drop unregion2 ADM0 ID_adm1, force
tempfile continents
save `continents', replace 
restore



/*
Create the following matrix: rows for statistics, 4 columns for different aid donors

*/

//build matrix frame
matrix A = J(10,2,.) //get empty matrix, add 1 more row for title of variable
matrix colnames A = "WB IDA" "China" //"India" "WB IBRD" 
matrix rownames A = "Total aid after cleaning (M\\$)" "Active in No of countries"  "No of projects coded" "No of project locations"    "Mean per Project (M\\$)" "Mean per Location (M\\$)" "Average No of Locations/Project" "Recipient Region  w. conflict (\%)" "Share of Aid to Democracies (\%)" "Countries w. Aid of Both Donors (\%)"

//variable list
global var_list WBAID_ADM1_LOC  CAID_ADM1_LOC // IAID_ADM1_LOC IBRD_ADM1_LOC

//count number of items in var_list
global numitems = wordcount("$var_list") 
//qui{
	//loop over all variables to fill out matrix ("x" is the numbered item in matrix, "var" is the selected variable)
	forvalues x =1/$numitems {
	//get name of variable, selected by ith entry in list
	local var : word `x' of $var_list //get variable name back
	//display variable name as control
*	di "`var'"
	***************************
	******fill out matrix******
	***************************
		//Total aid amount after cleaning
*********************************************

	use "$data\Merge\IDA_Aid_GED_ADM1.dta", clear

// drop small economies and islands
drop if d_smallcountry ==1
* keep only Africa in dataset
keep if unregion2=="Africa"

	gen `var'_m =`var'/1000000
	egen `var'_ttotalaid=total(`var'_m)
	sum `var'_ttotalaid
	assert `r(mean)' ==`r(max)'
	matrix A[1,`x']= `r(mean)' 

	
	//Number of recipient countries
*********************************************
	if "`var'"=="CAID_ADM1_LOC" { 
		 use "$data\Merge\IDA_Aid_GED_ADM1.dta", clear
		keep if CAID_ADM1_LOC!=. & CAID_ADM1_LOC!=0	
// drop small economies and islands
drop if d_smallcountry ==1
* keep only Africa in dataset
keep if unregion2=="Africa"
duplicates drop ISO3, force
		levelsof ISO3 , local(list) 
	}
	else {
	use "$data\Merge\IDA_Aid_GED_ADM1.dta", clear

// drop small economies and islands
drop if d_smallcountry ==1
* keep only Africa in dataset
keep if unregion2=="Africa"

	keep if WBAID_ADM1_LOC!=0 & WBAID_ADM1_LOC!=.
	duplicates drop ISO3, force
		levelsof ISO3 if `var'!=., local(list)
	}
	local count: word count(`list')
	* Substract 1 since count starts with 1 by default
	matrix A[2,`x']= `count' -1
	

	preserve
	use `continents', clear
	duplicates drop ADM0 unregion2 , force
		keep ADM0 unregion2 d_smallcountry
	tempfile continents

	save `continents', replace
	restore
	//"No. of projects coded (all)" 
*********************************************
	if "`var'"=="CAID_ADM1_LOC" { 
		preserve
		use "$data\Aid\ChinaAid_projects_clean.dta", clear
		rename adm0_namec254 ADM0
		merge m:1 ADM0  using `continents'
		drop if usd_current==.
		keep if (precision_n100<=4)  
				keep if  unregion2=="Africa" 				
		keep if  flow_class=="ODA-like" 
				drop if  d_smallcountry==1
				levelsof project_id, local(list)
				restore
	}
	
	if "`var'"=="WBAID_ADM1_LOC" { 
		preserve
		use "$data\Aid\IDA_disbursement.dta", clear
		merge m:1 ADM0  using `continents'
		keep if (precision_N100<=4)  
				keep if  unregion2=="Africa" 
				drop if  d_smallcountry==1

				levelsof project_id, local(list) 
		restore
	}	
	
	local count: word count(`list')
		* Substract 1 since count starts with 1 by default
	matrix A[3,`x']= `count'
		

	//"No. of locations (all)" 
*********************************************
	if "`var'"=="CAID_ADM1_LOC" { 
		preserve
use "$data\Merge\IDA_Aid_GED_ADM1.dta", clear
keep unregion2 ADM0 ID_adm1 d_smallcountry
duplicates drop unregion2 ADM0 , force
tempfile continents
save `continents', replace 
restore
		import excel using "$data\Aid\aiddata_china_1_1_1.xlsx", sheet("1) Official Finance") firstrow clear
keep project_id usd_current
tempfile usd_current
save `usd_current', replace

		import excel using "$data\Aid\aiddata_china_1_1_1.xlsx", sheet("2) Official Finance Locations") firstrow clear
		rename ADM0_NAME ADM0
		merge m:1 ADM0  using `continents', nogen
		merge m:1 project_id using `usd_current', nogen
		drop if usd_current==.
		keep if (precision_code<=4)  
				keep if  unregion2=="Africa" 
		keep if  flow_class=="ODA-like" 
				drop if  d_smallcountry==1
				duplicates drop project_id latitude longitude, force
								gen p="p"
				gen r="r"
				egen project_location_id = concat(p project_id r geonameID)
				levelsof project_location_id, local(list)
	}	
	if "`var'"=="WBAID_ADM1_LOC" { 
		preserve
use "$data\Merge\IDA_Aid_GED_ADM1.dta", clear
keep unregion2 ADM0 ID_adm1 d_smallcountry
duplicates drop unregion2 ADM0 , force
tempfile continents
save `continents', replace 
restore
		use "$data\Aid\IDA_disbursement.dta", clear
		merge m:1 ADM0  using `continents'
		keep if (precision_N100<=4)  
		keep if  unregion2=="Africa" 
				drop if  d_smallcountry==1

				levelsof project_loC254, local(list) 

	}	
						local count: word count(`list')

		* Substract 1 since count starts with 1 by default
	matrix A[4,`x']= `count'-1

			//Share Aid to Regions with Any Conflict in Panel
*********************************************

use "$data\working_file.dta", clear
// drop small economies and islands
drop if d_smallcountry ==1
* keep only Africa in dataset
keep if unregion2=="Africa"

sum inten1_adm1 if `var'!=0 & `var'!=.
	assert `r(mean)' ==`r(mean)'
	matrix A[8,`x']= `r(mean)'
	

				//Share Aid to Democracies
*********************************************
use "$data\working_file.dta", clear
// drop small economies and islands
drop if d_smallcountry ==1
* keep only Africa in dataset
keep if unregion2=="Africa"

* Aid to democracies
egen total_`var'_demo=total(`var') if democracy_br==1
egen total_`var'_ndemo=total(`var') if democracy_br==0

foreach i in demo ndemo {
rename total_`var'_`i' aux_`var'_`i'
egen total_`var'_`i'=max(aux_`var'_`i')
}
gen share_`var'_demo=total_`var'_demo/(total_`var'_demo+total_`var'_ndemo)
sum share_`var'_demo
	assert `r(mean)' ==`r(mean)'
	matrix A[9,`x']= `r(mean)' *100
	drop total_`var'_demo total_`var'_ndemo  aux* share_`var'_demo

		
		}
			//Mean per Project (Million USD)
*********************************************
	matrix A[5,1]= A[1,1]/A[3,1]
	matrix A[5,2]= A[1,2]/A[3,2]

			//Mean per Location (Million USD)
*********************************************		
	matrix A[6,1]= A[1,1]/A[4,1]
	matrix A[6,2]= A[1,2]/A[4,2]

				//Average No of Locations/Project
*********************************************
	matrix A[7,1]= A[4,1]/A[3,1]
	matrix A[7,2]= A[4,2]/A[3,2]

	
					//Share of Countries with Aid from both donors
*********************************************
		 use "$data\Merge\IDA_Aid_GED_ADM1.dta", clear
		 // drop small economies and islands
drop if d_smallcountry ==1
* keep only Africa in dataset
keep if unregion2=="Africa"

gen WBAID=0
replace WBAID=1 if WBAID_ADM1_LOC!=. & WBAID_ADM1_LOC!=0 
gen CAID=0
replace CAID=1 if CAID_ADM1_LOC!=. & CAID_ADM1_LOC!=0 
bysort ADM0: egen max_WBAID=max(WBAID)
bysort ADM0: egen max_CAID=max(CAID)
gen bothaid=0
replace bothaid=1 if max_WBAID==1 & max_CAID==1
duplicates drop ADM0, force
keep if max_WBAID!=0 | max_CAID!=0
sum bothaid
	matrix A[10,1]= `r(mean)' *100
	matrix A[10,2]= `r(mean)' *100



	******Matrix fill end********
	//}
//build table out of matrix
cd "$tables"
frmttable using describeAid, hlines(11{0}1) tex fragment statmat(A) sdec(0 \0 \0 \0 \2\2\0\2\2\2) sfmt("f","f","f","f","f","f","f","f","f" \ "f","f","f","f","f","f","f","f","f" \ "fc","fc","fc","fc","fc","fc","fc","fc","fc") replace

******************************************************
****************************************************
* Table 2: Descriptive Statistics - ADM1 Regions 
use "$data\Merge\IDA_Aid_GED_ADM1.dta", clear

* keep only African dataset
keep if unregion2=="Africa"

// drop small economies and islands
drop if d_smallcountry ==1

gen inten1_adm1=0
replace inten1_adm1=100 if brd_adm1>=5

gen lnaid=ln(WBAID_ADM1_LOC+0.01)
gen lnaid_c=ln(CAID_ADM1_LOC+0.01)

* Rescale for Percentage interpretation
replace D_total_rds = D_total_rds*100
replace D_pro_gov_vio_nleth=D_pro_gov_vio_nleth*100
replace D_repress_nl=D_repress_nl*100

matrix A = J(7,4,.) //get empty matrix, add 1 more row for title of variable
matrix colnames A = "Mean" "SD" "Min" "Max" 
matrix rownames A =  "World Bank Aid" "ln(WB Aid)" "Chinese Aid" "ln(Chinese Aid)"  "Riots, Strikes, Demonstrations in Perc." "Repression Incidence in Perc." "Conflict Incidence in Perc."
local i=1
foreach var in WBAID_ADM1_LOC lnaid CAID_ADM1_LOC lnaid_c D_total_rds D_repress_nl inten1_adm1 {
sum `var'
matrix A[`i',1]= `r(mean)' 
matrix A[`i',2]= `r(sd)' 
matrix A[`i',3]= `r(min)' 
matrix A[`i',4]= `r(max)' 
local i = `i'+1
}


cd "$tables"
frmttable using descriptives_adm1_test, hlines(11{0}1) fragment tex statmat(A) sdec(1,1,1,1) replace //sfmt("f","f","f","f" \ "f","f","f","f" \ "fc","fc","fc","fc") 
// reduce space after table
filefilter descriptives_adm1_test.tex descriptives_adm1.tex, from("{\BSsmallskip}\BSend{tabular}") to ("{\BSvspace{-5mm}}\BSend{tabular}") replace
sleep 5000
rm "descriptives_adm1_test.tex"





use "$data\Merge\IDA_Aid_GED_ADM1.dta", clear
* keep only African dataset
keep if unregion2=="Africa"

gen inten1_adm1=0
replace inten1_adm1=100 if brd_adm1>=5

foreach i in t1_adm1 t2_adm1 t3g_adm1 t3ng_adm1 {
	* Conflict Data
	* Genreate new intensity thresholds
	gen inten1_`i'=0
	replace inten1_`i'=100 if brd_`i'>=5
	}
	
	foreach i in  D_total_rds D_demo D_riot D_strike D_repress_nl {
	replace `i'=`i'*100
	}

matrix B = J(10,4,.) //get empty matrix, add 1 more row for title of variable
matrix colnames B = "Mean" "SD" "Min" "Max" 
matrix rownames B =  "Conflict Incidence" "State Based Conflict" "Non-State Based Conflict" "State Violence vs Civilians" "Non-State Violence vs Civilians" "Riots, Strikes \& Demonstrations"  "Riots"  "Strikes"  "Demonstrations" "Non-lethal Government Repression"
local i=1
	
foreach var in inten1_adm1  inten1_t1_adm1 inten1_t2_adm1 inten1_t3g_adm1 inten1_t3ng_adm1  D_total_rds D_demo D_riot D_strike D_repress_nl {
sum `var'
matrix B[`i',1]= `r(mean)' 
matrix B[`i',2]= `r(sd)' 
matrix B[`i',3]= `r(min)' 
matrix B[`i',4]= `r(max)' 
local i = `i'+1
}

cd "$tables"
frmttable using descriptives_adm1_conflicts, hlines(11{0}1) fragment tex statmat(B) sdec(2,2,0,0) replace //sfmt("f","f","f","f" \ "f","f","f","f" \ "fc","fc","fc","fc") 
// reduce space after table
filefilter descriptives_adm1_conflicts.tex descriptives_adm1_conflict.tex, from("{\BSsmallskip}\BSend{tabular}") to ("{\BSvspace{-5mm}}\BSend{tabular}") replace
rm "descriptives_adm1_conflict.tex"



************************************************************************
* Table 5: Conflict History and Reporting of Chinese Aid:
************************************************************************
use "$data\working_file.dta", clear


* Rescale press freedom
gen PressFreedom_Score_inv=-PressFreedom_Score


xtile btransp= transparencyindex if transparencyindex!=., n(2)
xtile bpress= PressFreedom_Score_inv if PressFreedom_Score_inv!=., n(2)

gen l1inten1_adm1=l1.inten1_adm1
* China
bysort ID_adm1_num: gen conf_hist=sum(l1inten1_adm1)
foreach var in  btransp bpress {
sum CAID_ADM1_LOC if `var'==1
sum CAID_ADM1_LOC if `var'==2
sum CAID_ADM1_LOC if `var'==1 & conf_hist==0
sum CAID_ADM1_LOC if `var'==1 & conf_hist>0
sum CAID_ADM1_LOC if `var'==2 & conf_hist==0
sum CAID_ADM1_LOC if `var'==2 & conf_hist>0
}

foreach var in  bpress {
sum CAID_ADM1_LOC if `var'==1
sum CAID_ADM1_LOC if `var'==2
sum CAID_ADM1_LOC if `var'==1 & inten1_adm1==0
sum CAID_ADM1_LOC if `var'==1 & inten1_adm1==100
sum CAID_ADM1_LOC if `var'==2 & inten1_adm1==0
sum CAID_ADM1_LOC if `var'==2 & inten1_adm1==100
}

*WB
foreach var in   bpress {
sum WBAID_ADM1_LOC if `var'==1
sum WBAID_ADM1_LOC if `var'==2
sum WBAID_ADM1_LOC if `var'==1 & conf_hist==0
sum WBAID_ADM1_LOC if `var'==1 & conf_hist>0
sum WBAID_ADM1_LOC if `var'==2 & conf_hist==0
sum WBAID_ADM1_LOC if `var'==2 & conf_hist>0
}

foreach var in  bpress {
sum WBAID_ADM1_LOC if `var'==1
sum WBAID_ADM1_LOC if `var'==2
sum WBAID_ADM1_LOC if `var'==1 & inten1_adm1==0
sum WBAID_ADM1_LOC if `var'==1 & inten1_adm1==100
sum WBAID_ADM1_LOC if `var'==2 & inten1_adm1==0
sum WBAID_ADM1_LOC if `var'==2 & inten1_adm1==100
}



*******************
* Analyses		 *
*******************
* Table in paper: "ADM1  OLS results (Aid and Conflict at the Local Level)" 
**************** Country level results

use "$data\working_file.dta", clear
local DepVar inten1_adm1 // D_pro_gov_v_nl_adm1 D_pro_gov_v_l_adm1  N_pro_gov_vio_leth  N_pro_gov_violence  N_pro_gov_vio_nleth D_riot_adm1 D_strike_adm1 D_demo_adm1 lnbrd_adm1 D_tot_rds_adm1 D_pro_gov_v_adm1 D_tot_v_adm1 inten2_adm1 
local TreatVar l1.lnaid `"l2.lnaid_c"' l1.lnaid_pop l2.lnaid_pop_c  
local cluster  fr  `"fcy fr"' //    `"i.state#i.transaction_year"' 


foreach g in `DepVar' {
	foreach t in l1.std_lnaid l2.std_lnaid_c {
		foreach c in `cluster' {
			if "`t'"=="l2.lnaid_c"{
				* Set endogenous controls with one further lag for Chinese aid as we use commitments with two lags
				global control3 L3.drug_y L3.gem_y  L3.isum_pop_ADM1 L3.goldsurface_y L3.diamprim_y L3.diamsec_y L3.petroleum_y L3.excluded  L3.ln_IBRD_ADM1_LOC L3.lights_sum
			}
			if "`t'"=="l1.lnaid"{
				* Set endogenous controls for WB
				global control3 L2.drug_y L2.gem_y  L2.isum_pop_ADM1 L2.goldsurface_y L2.diamprim_y L2.diamsec_y L2.petroleum_y L2.excluded  L2.ln_IBRD_ADM1_LOC L2.lights_sum
			}

			//1. Country level regressions (preserve to restore once more data on administrative level)
						di "Run regression for dependent variable: `g', treatvar: `t', and cluster level `c'"
			eststo clear
					preserve	
		* Including project aid that was not precisely geocoded

			use "$data/working_file_country.dta", clear
			renvars lnaid_country lnaid_c_country / lnaid lnaid_c
			xtset state transaction_year 
			sort state transaction_year 

			*Standard Deviation as Treatment
			cap drop std_lnaid std_lnaid_c
				egen std_lnaid=std(lnaid), mean(0)  std(1)
			egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)
			* Model 1 - state and year FE
			reghdfe inten2_country  `t', absorb(i.transaction_year i.state )  cluster(state)				
			eststo		
			restore

		* Excluding project aid that was not precisely geocoded
			preserve
			use "$data/working_file_country.dta", clear
			renvars lnaid_country_nobudget lnaid_c_country_nobudget / lnaid lnaid_c
			xtset state transaction_year 
			sort state transaction_year 

			*Standard Deviation as Treatment
			cap drop std_lnaid std_lnaid_c
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)
* Model 1 - state and year FE
			reghdfe inten2_country  `t', absorb(i.transaction_year i.state )  cluster(state)				
			eststo	
* Model 2 - state and year FE - lower intensity
			reghdfe inten1_country  `t', absorb(i.transaction_year i.state )  cluster(state)				
			eststo	


restore


			
				*Standard Deviation as Treatment
			cap drop std_lnaid std_lnaid_c
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)
		


			//1. country FE + transaction_year Fe
			quietly reghdfe `g' `t', cluster(`c') absorb(i.state i.transaction_year)
			eststo

			//2. continental trend + country FE + transaction_year Fe + country trends
			quietly reghdfe `g' `t', cluster(`c') absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.state#c.trend i.state#c.trend_sq)
			eststo


			//3. continental trend + country FE + transaction_year Fe + country trends + Region FE 
			quietly reghdfe `g' `t', cluster(`c') absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.state#c.trend i.state#c.trend_sq i.ID_adm1_num)
			eststo

			//4. continental trend + country FE + transaction_year Fe + Region FE + country trends + D1 and D3  + quadratic country trend + region trend
			quietly reghdfe `g' `t' $control2 , cluster(`c') absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend)
			eststo

			//5. continental trend + country FE + transaction_year Fe + Region FE + D1 and D3 + continental trend + quadratic country trend + region trend + Country-Transaction_year FE
			quietly reghdfe `g' `t' $control2, cluster(`c') absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend i.state#i.transaction_year)
			eststo

			//9. continental trend + country FE + transaction_year Fe + Region FE + D1 and D3 + continental trend + quadratic country trend + region trend + Country-Transaction_year FE  + endogeneous controls
			 reghdfe `g' `t' $control2 $control3, cluster(`c') absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend i.state#i.transaction_year)
			eststo


			//table for all regressions
			* Prepare estimates for -estout-
			estfe _all, labels( ///
				state "Country FE" ///
				transaction_year "Transaction_year FE" ///
				ID_adm1_num "Region FE" ///
				continent_num#transaction_year "Time Trends" ///
				ID_adm1_num#c.trend "Regional Trend" ///
				ID_adm1_num#c.trend_sq "Quadratic Regional Trend" ///
				state#transaction_year "Country-Transaction_year FE")
			return list
			di ""`r(indicate_fe)'""
			* Indicate different Table names depending on cluster
			if "`t'"=="l1.std_lnaid" & "`c'"=="fcy fr"{
				esttab _all using "$tables\cluster2multi_wb_`g'.tex", replace booktabs fragment keep(L.std_lnaid)  stats(N r2, fmt(%9.0g %9.3f) labels(N R-squared))  coeflabels(L.std_lnaid "ln(World\,Bank\,Aid\,\textsubscript{t-1})") ///
				se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress nomtitles parentheses nonumbers noline nogap
			}
			if "`t'"=="l1.std_lnaid" & "`c'"=="fr" {
				esttab _all using "$tables\cluster2region_wb_`g'", replace booktabs fragment keep(L.std_lnaid)  stats(N r2, fmt(%9.0g %9.3f ) labels(N R-squared))  coeflabels(L.std_lnaid "ln(World\,Bank\,Aid\,\textsubscript{t-1})") ///
				se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress nomtitles parentheses nonumbers noline nogap
			}
			if "`t'"=="l1.std_lnaid" & "`c'"=="i.state#i.transaction_year" {
				esttab _all using "$tables\cluster2countryyear_wb_`g'", replace booktabs fragment keep(L.std_lnaid)  stats(N r2, fmt(%9.0g %9.3f) labels(N R-squared)) coeflabels(L.std_lnaid "ln(World\,Bank\,Aid\,\textsubscript{t-1})") ///
				se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress nomtitles parentheses nonumbers noline nogap  
			}
			if "`t'"=="l2.std_lnaid_c" & "`c'"=="fcy fr" {
				esttab _all using "$tables\cluster2multi_china_`g'", replace booktabs fragment keep(L2.std_lnaid_c )  stats(N r2, fmt(%9.0g %9.3f) labels(N R-squared)) coeflabels(L2.std_lnaid_c "ln(Chinese\,Aid\,\textsubscript{t-2})") ///
				se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress nomtitles parentheses nonumbers noline nogap 
			}
			if "`t'"=="l2.std_lnaid_c" & "`c'"=="fr" {
				esttab _all using "$tables\cluster2region_china_`g'", replace booktabs fragment keep(L2.std_lnaid_c ) stats(N r2, fmt(%9.0g %9.3f) labels(N R-squared)) coeflabels(L2.std_lnaid_c "ln(Chinese\,Aid\,\textsubscript{t-2})") ///
				se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress nomtitles parentheses nonumbers noline nogap 
			}
			if "`t'"=="l2.std_lnaid_c" & "`c'"=="i.state#i.transaction_year" {
				esttab _all using "$tables\cluster2countryyear_china_`g'", replace booktabs fragment keep(L2.std_lnaid_c )  stats(N r2, fmt(%9.0g %9.3f) labels(N R-squared)) coeflabels(L2.std_lnaid_c "ln(Chinese\,Aid\,\textsubscript{t-2})") ///
				se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress nomtitles parentheses nonumbers noline nogap 
}
				
mata: mata clear				
				* Oster
				 * Define Matrices
clear matrix
mat A = J(1,2,.)
			*	matrix input A=(0,0)
*************country + year dummies vs. all wo trend
 *Oster
 reghdfe `g' `t' ,absorb(i.state i.transaction_year) cluster(i.state#i.transaction_year i.ID_adm1_num)
scalar Rmin=e(r2)
 scalar Betamin=_b[`t' ]
reghdfe `g'   `t' $control2, cluster(`c') absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend i.state#i.transaction_year)
scalar RMAX=min(1,2.2*e(r2))
 scalar Rtilda=e(r2)
scalar Betatilda=_b[`t']
scalar deltaOster=1
scalar BetaIden1=Betatilda-deltaOster*(Betamin-Betatilda)*(RMAX-Rtilda)/(Rtilda-Rmin)
estadd scalar BetaIden1=Betatilda-deltaOster*(Betamin-Betatilda)*(RMAX-Rtilda)/(Rtilda-Rmin)
matrix A[1,1]=BetaIden1
matrix A[1,2]=Betamin
mat list A

				
				if "`t'"=="l2.std_lnaid_c" {			
estout matrix(A, fmt(%9.2f ) )using "$tables\cluster2multi_china_`g'.tex",append    ///
style(tab) delimiter(_tab ) title() incelldelimiter(";") ///
labcol2("Identified $\beta$-set (Oster) & &	 & & & & " )
			}
							if "`t'"=="l1.std_lnaid" {			
estout matrix(A, fmt(%9.2f ) )using "$tables\cluster2multi_wb_`g'.tex",append ///
style(tab) delimiter(_tab ) title() incelldelimiter(";") ///
labcol2("Identified $\beta$-set (Oster) & &	 & & & & " )
			}
			
		}
	}
}


******************************
* Selection-on-unobservables *
******************************
eststo clear
mata: mata clear

				*Standard Deviation as Treatment
			cap drop std_lnaid std_lnaid_c
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)

foreach var in  t1 t2 t3g t3ng {
	gen inten1_`var'_adm1=0
	replace inten1_`var'_adm1=100 if brd_`var'_adm1>=5
	}
foreach var in inten1_adm1 inten1_t1_adm1 inten1_t2_adm1 inten1_t3g_adm1 inten1_t3ng_adm1 D_repress_nl D_tot_rds_adm1 {
matrix input A=(0,0,0,0,0,0,0 \ 0,0,0,0,0,0 ,0 \ 0,0,0 ,0,0,0,0\ 0,0,0,0,0,0,0)
*************country + year dummies vs. all wo trend
 local no=1
 
 * World Bank
 reghdfe `var' l1.std_lnaid ,absorb(i.state i.transaction_year) cluster(i.state#i.transaction_year i.ID_adm1_num)
scalar B1_l=_b[L.std_lnaid]
scalar SE1_l=_se[L.std_lnaid]
reghdfe `var'    l1.std_lnaid $control2, cluster(`c') absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend i.state#i.transaction_year)
scalar B1_f=_b[L.std_lnaid]
scalar SE1_f=_se[L.std_lnaid]
scalar ratio=B1_f/(B1_l-B1_f)
matrix A[`no',7]=abs(B1_f/(B1_l-B1_f))
matrix A[`no',1]=B1_l
matrix A[`no',3]=B1_f
matrix A[`no',2]=SE1_l
matrix A[`no',4]=SE1_f
*Oster
 reghdfe `var' l1.std_lnaid ,absorb(i.state i.transaction_year) cluster(i.state#i.transaction_year i.ID_adm1_num)
scalar Rmin=e(r2)
 scalar Betamin=_b[L.std_lnaid]
reghdfe `var'  l1.std_lnaid $control2, cluster(`c') absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend i.state#i.transaction_year)
scalar RMAX=min(1,2.2*e(r2))
 scalar Rtilda=e(r2)
scalar Betatilda=_b[L.std_lnaid]
scalar deltaOster=1
scalar BetaIden1=Betatilda-deltaOster*(Betamin-Betatilda)*(RMAX-Rtilda)/(Rtilda-Rmin)
estadd scalar BetaIden1=Betatilda-deltaOster*(Betamin-Betatilda)*(RMAX-Rtilda)/(Rtilda-Rmin)
if BetaIden1<=Betamin{		
matrix A[`no',5]=BetaIden1
matrix A[`no',6]=Betamin
}
if Betamin<=BetaIden1{		
matrix A[`no',5]=Betamin
matrix A[`no',6]=BetaIden1
}
mat list A

matrix B = A[1,1..7]
mat list B
matrix rownames B =  "1"
estout matrix(B, fmt(%9.2f ) )using "$tables\Table_Oster_`var'.txt",replace    collabels(b1u b1r ratio) ///
style(tab) delimiter(_tab ) title()  ///
labcol2("(Column 1) vs (Column 8)" )

* China
 local no=2
 
reghdfe `var'  l2.std_lnaid_c , absorb(i.state i.transaction_year)  cluster(i.state#i.transaction_year i.ID_adm1_num) 
scalar B1_l=_b[L2.std_lnaid_c]
scalar SE1_l=_se[L2.std_lnaid_c]
reghdfe `var'  l2.std_lnaid_c $control2, cluster(`c') absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend i.state#i.transaction_year)
scalar B1_f=_b[L2.std_lnaid_c]
scalar SE1_f=_se[L2.std_lnaid_c]
scalar ratio=B1_f/(B1_l-B1_f)
matrix A[`no',7]=abs(B1_f/(B1_l-B1_f))
matrix A[`no',1]=B1_l
matrix A[`no',3]=B1_f
matrix A[`no',2]=SE1_l
matrix A[`no',4]=SE1_f
*Oster
reghdfe `var'  l2.std_lnaid_c , absorb(i.state i.transaction_year)  cluster(i.state#i.transaction_year i.ID_adm1_num) 
scalar Rmin=e(r2)
 scalar Betamin=_b[L2.std_lnaid_c]
* psacalc2 beta L.std_lnaid, delta(0.5)
reghdfe `var' l2.std_lnaid_c $control2, cluster(`c') absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend i.state#i.transaction_year)
* psacalc2 beta L.std_lnaid, delta(1) 
scalar RMAX=min(1,2.2*e(r2))
 scalar Rtilda=e(r2)
scalar Betatilda=_b[L2.std_lnaid_c]
scalar deltaOster=1
scalar BetaIden1=Betatilda-deltaOster*(Betamin-Betatilda)*(RMAX-Rtilda)/(Rtilda-Rmin)
estadd scalar BetaIden1=Betatilda-deltaOster*(Betamin-Betatilda)*(RMAX-Rtilda)/(Rtilda-Rmin)
if BetaIden1<=Betamin{		
matrix A[`no',5]=BetaIden1
matrix A[`no',6]=Betamin
}
if Betamin<=BetaIden1{		
matrix A[`no',5]=Betamin
matrix A[`no',6]=BetaIden1
}
mat list A

matrix B = A[2,1..7]
mat list B
matrix rownames B =  "2"
estout matrix(B, fmt(%9.2f ) )using "$tables\Table_Oster_`var'.txt",append   collabels(b1u b1r ratio) ///
style(tab) delimiter(_tab ) title()  ///
labcol2("(Column 1) vs (Column 8)" )
}

*/

****************************
*		OLS Robustness	   *
****************************
* Table in paper: "Table 30: Full Regression Results - Controlled for Country Level Press Freedom Interacted With Region FE (1)"
foreach z in t1 t2 t3g t3ng { 
capture drop inten1_`z'_adm1
gen inten1_`z'_adm1=0
replace inten1_`z'_adm1=100 if brd_`z'_adm1>=5 & brd_`z'_adm1!=.
}
*eststo clear
foreach g in inten1_adm1 inten1_t1_adm1 inten1_t2_adm1 inten1_t3g_adm1 inten1_t3ng_adm1 D_tot_rds_adm1  D_repress_nl {
	foreach t in `TreatVar'{
			if "`t'"=="l2.lnaid_c"{
				* Set endogenous controls with one further lage for Chinese aid as we use commitments with two lags
				global control3 L3.drug_y L3.gem_y  L3.isum_pop_ADM1 L3.goldsurface_y L3.diamprim_y L3.diamsec_y L3.petroleum_y L3.excluded  L3.ln_IBRD_ADM1_LOC L3.lights_sum
				global control_press c.L3.PressFreedom_Score#i.ID_adm1_num
global control_transp c.L3.transparencyindex#i.ID_adm1_num
			}
			if "`t'"=="l1.lnaid"{
				* Set endogenous controls for WB
				global control3 L2.drug_y L2.gem_y  L2.isum_pop_ADM1 L2.goldsurface_y L2.diamprim_y L2.diamsec_y L2.petroleum_y L2.excluded  L2.ln_IBRD_ADM1_LOC L2.lights_sum
				global control_press c.L2.PressFreedom_Score#i.ID_adm1_num
global control_transp c.L2.transparencyindex#i.ID_adm1_num
			}

			di "Run regression for dependent variable: `g', treatvar: `t', and cluster level `c'"

			*7. continental trend + country FE + transaction_year Fe + Region FE + D1 and D3  + endogenous controls quadratic country trend + region trend
			reghdfe `g' `t' $control2 $control3  $control_press, cluster(fcy fr) absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend)			
			if "`t'"=="l1.lnaid"{
				eststo WB_`g'_1
			}
			if "`t'"=="l2.lnaid_c"{
				eststo China_`g'_1
			}

				*9. continental trend + country FE + transaction_year Fe + Region FE + D1 and D3 + continental trend + quadratic country trend + region trend + Country-Transaction_year FE  + endogeneous controls
			reghdfe `g' `t' $control2 $control3  $control_press,  cluster(fcy fr) absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend i.state#i.transaction_year)
			if "`t'"=="l1.lnaid"{
				eststo WB_`g'_2
			}
			if "`t'"=="l2.lnaid_c"{
				eststo China_`g'_2
			}
			

			*table for all regressions
			* Prepare estimates for -estout-
			estfe _all, labels( ///
				state "Country FE" ///
				transaction_year "Transaction_year FE" ///
				ID_adm1_num "Region FE" ///
				continent_num#transaction_year "Time Trends" ///
				ID_adm1_num#c.trend "Regional Trend" ///
				ID_adm1_num#c.trend_sq "Quadratic Regional Trend" ///
				state#transaction_year "Country-Transaction_year FE")
			return list
			di ""`r(indicate_fe)'""

	}
}				
				esttab China_inten1_adm1_1 China_inten1_adm1_2 China_inten1_t1_adm1_1 China_inten1_t1_adm1_2 China_inten1_t2_adm1_1 China_inten1_t2_adm1_2 China_inten1_t3g_adm1_1 China_inten1_t3g_adm1_2 China_inten1_t3ng_adm1_1 China_inten1_t3ng_adm1_2 using "$tables\cluster2multi_china_media_split1", replace booktabs fragment keep(L2.lnaid_c ) coeflabels(L2.lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$")se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress nomtitles parentheses nonumbers noline nogap 
								esttab China_D_tot_rds_adm1_1 China_D_tot_rds_adm1_2  China_D_repress_nl_1 China_D_repress_nl_2 using "$tables\cluster2multi_china_media_split2", replace booktabs fragment keep(L2.lnaid_c ) coeflabels(L2.lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$") se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress nomtitles parentheses nonumbers noline nogap 
				
	
		
		


****************************
* OLS Heterogenous effects *
****************************
eststo clear
* Table in paper: "Table 29: FE – Aid Sectors and Conflict"

drop lnaid 
foreach a in  AX BX CX EX FX JX LX TX WX YX {
	gen lnaid=ln(WBAID_ADM1_LOC_`a'+0.01)
	
	label var lnaid  "Log of location weighted WB aid per capita +0.01"
	
	cap drop std_lnaid 
	egen std_lnaid=std(lnaid), mean(0)  std(1)
	* Column (6)
	reghdfe inten1_adm1 $control2  l1.std_lnaid  if transaction_year>1995, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo AT_WB_ols_inten1_cy2_`a'

	* Column (8)
	reghdfe inten1_adm1 $control2 l1.std_lnaid if transaction_year>1995, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo AT_WB_ols_inten1_cy3_`a'
	drop lnaid

}
esttab AT_WB_ols_inten1_cy2* using "$tables\Aid_Subtypes_multi_OLS_wb_adm1", replace booktabs fragment keep(L.std_lnaid) coeflabels(L.std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-1})$") ///
se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress mtitles("AX" "BX" "CX" "EX" "FX" "JX" "LX" "TX" "WX" "YX") prehead("Panel A: No Country-Year FE") nonumbers noline nogap noobs postfoot(\hline)

esttab AT_WB_ols_inten1_cy3* using "$tables\Aid_Subtypes_multi_OLS_wb_adm1", append  booktabs fragment keep(L.std_lnaid) coeflabels(L.std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-1})$") ///
se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress nomtitles parentheses prehead("Panel B: Country-Year FE \\")  ///
nonumbers noline nogap


drop lnaid_c
foreach a in  AX BX CX EX  JX LX TX WX YX {
	gen lnaid_c=ln(CAID_ADM1_LOC_`a'+0.01)
	
	label var lnaid_c  "Log of location weighted Chinese aid per capita +0.01"
	
	cap drop  std_lnaid_c
	egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)


	* Column (6)
	reghdfe inten1_adm1 $control2 l2.std_lnaid_c  if transaction_year>1995, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo AT_CH_ols_inten1_cy2_`a'

	* Column (8)
	reghdfe inten1_adm1 $control2 l2.std_lnaid_c if transaction_year>1995, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo AT_CH_ols_inten1_cy3_`a'

	drop lnaid_c

}


esttab AT_CH_ols_inten1_cy2* using "$tables\Aid_Subtypes_multi_OLS_china_adm1", replace booktabs fragment keep(L2.std_lnaid_c) coeflabels(L2.std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$") ///
se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress mtitles("AX" "BX" "CX" "EX"  "JX" "LX" "TX" "WX" "YX") prehead("Panel C: No Country-Year FE") nonumbers noline nogap noobs postfoot(\hline)

esttab AT_CH_ols_inten1_cy3* using "$tables\Aid_Subtypes_multi_OLS_china_adm1", append  booktabs fragment keep(L2.std_lnaid_c) coeflabels(L2.std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$") ///
se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) nomtitles parentheses prehead("Panel D:Country-Year FE \\")  ///
nonumbers noline nogap
//replace latex string manually
filefilter "$tables\Aid_Subtypes_multi_OLS_china_adm1.tex" "$tables\test.tex", from("oL2.lnaid\BS_c&                  &                  &                  &                  &   0.0000         &                  &                  &                  &                  &                  \BS\BS") to("") replace
filefilter "$tables\test.tex" "$tables\test1.tex", from("oL2.lnaid\BS_c &                     &                     &                     &                     &      0.0000         &                     &                     &                     &                     &                     \BS\BS") to("") replace
filefilter "$tables\test1.tex" "$tables\test2.tex", from("          &                  &                  &                  &                  &      (.)         &                  &                  &                  &                  &                  \BS\BS") to("") replace
filefilter "$tables\test2.tex" "$tables\test3.tex", from("                      &                     &                     &                     &                     &         (.)         &                     &                     &                     &                     &                     \BS\BS") to("") replace
filefilter "$tables\test3.tex" "$tables\Aid_Subtypes_multi_china_adm1_clean.tex", from("            &                     &                     &                     &                     &         (.)         &                     &                     &                     &                     &                     \BS\BS") to("") replace

* Restore log of total aid and IV for total aid
* Log of aid
gen lnaid=ln(WBAID_ADM1_LOC+0.01)
label var lnaid  "Log of location weighted World Bank Aid per capita +0.01"
gen lnaid_c=ln(CAID_ADM1_LOC+0.01)
label var lnaid_c  "Log of location weighted Chinese Aid per capita +0.01"


***********************
* Lead and lag        *
***********************
* Estimate with treatment in standard deviations

cap drop std_lnaid std_lnaid_c 
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)



eststo clear
* World Bank
* Column (6)
reghdfe inten1_adm1 $control2 l(-1,0,1,2,3).std_lnaid, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq)  cluster(i.state#i.transaction_year i.ID_adm1_num)
eststo LL_inten1_cy2

* Column (8)
reghdfe inten1_adm1 $control2 l(-1,0,1,2,3).std_lnaid, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq)  cluster(i.state#i.transaction_year i.ID_adm1_num)
eststo LL_inten1_cy3


esttab LL_inten1_cy* using "$tables\LL_multi_wb_adm1", replace booktabs fragment keep(F.std_lnaid std_lnaid L.std_lnaid L2.std_lnaid L3.std_lnaid) coeflabels(F.std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t+1})$" std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t})$" L.std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-1})$" L2.std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-2})$" L3.std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-3})$") ///
se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress nomtitle parentheses prehead("Lead and Lag: World Bank \\") ///
nonumbers noline nogap


* Chinese Aid
* Column (6)
reghdfe inten1_adm1 $control2  l(-1,0,1,2,3).std_lnaid_c, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq)  cluster(i.state#i.transaction_year i.ID_adm1_num)
eststo LL_inten1_cy2

* Column (8)
reghdfe inten1_adm1 $control2 l(-1,0,1,2,3).std_lnaid_c, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
eststo LL_inten1_cy3


esttab LL_inten1_cy* using "$tables\LL_multi_china_adm1", replace booktabs fragment keep(F.std_lnaid_c std_lnaid_c L.std_lnaid_c L2.std_lnaid_c L3.std_lnaid_c) coeflabels(F.std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t+1})$" std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t})$" L.std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-1})$" L2.std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$" L3.std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-3})$") ///
se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress  nomtitles parentheses prehead("Lead and Lag: China \\") ///
nonumbers noline nogap



**********************
* Further Leads and Lags   *
**********************
* Estimate with treatment in standard deviations

cap drop std_lnaid std_lnaid_c
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)


eststo clear
* World Bank
* Column (8)
parmby "reghdfe inten1_adm1 $control2 l(-1,0,1,2,3).std_lnaid, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq)  cluster(i.state#i.transaction_year i.ID_adm1_num)",saving("$tables\parmest_wb.dta") level(90 95 99 99.5) clnum(level)

preserve

u  "$tables\parmest_wb.dta", clear
keep if  parm=="F2.std_lnaid" | parm=="F.std_lnaid" | parm=="std_lnaid" | parm=="L.std_lnaid" | parm=="L2.std_lnaid" | parm=="L3.std_lnaid"

split parm, parse(.)
encode parm1, gen(timevar)
replace timevar=2 if parm=="F2.std_lnaid"
replace timevar=1 if parm=="F.std_lnaid"
replace timevar=0 if parm=="std_lnaid"
replace timevar=-1 if parm=="L.std_lnaid"
replace timevar=-2 if parm=="L2.std_lnaid"
replace timevar=-3 if parm=="L3.std_lnaid"

lab define newlabel  -3 "t-3" -2 "t-2" -1 "t-1" 0 "t" 1 "t+1" , modify // 
lab val timevar newlabel

eclplot estimate min90 max90 timevar, eplottype(connected) rplottype(rcap) yscale(range(-3 2)) ylabel(-3(0.5)2) xscale(range(-3 1)) xlabel(-3(1)1, angle(45)) yline(0) xtitle("log(WB Aid + 0.01)", size(medsmall))  ytitle("{&Delta} conflict(t)/{&Delta} log(WB Aid + 0.01)", size(medsmall)) graphregion( color(white))
graph export "$graphs\lags_leads_WB.png", as(png) name("Graph") replace
erase   "$tables\parmest_wb.dta"
restore

* Chinese Aid
* Column (8)
parmby "reghdfe inten1_adm1 $control2 l(-1,0,1,2,3).std_lnaid_c, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)", saving("$tables\parmest_china.dta") level(90 95 99 99.5) clnum(level)

preserve

use  "$tables\parmest_china.dta", clear
keep if  parm=="F.std_lnaid_c" | parm=="std_lnaid_c" | parm=="L.std_lnaid_c" | parm=="L2.std_lnaid_c" | parm=="L3.std_lnaid_c"

split parm, parse(.)
encode parm1, gen(timevar)
replace timevar=1 if parm=="F.std_lnaid_c"
replace timevar=0 if parm=="std_lnaid_c"
replace timevar=-1 if parm=="L.std_lnaid_c"
replace timevar=-2 if parm=="L2.std_lnaid_c"
replace timevar=-3 if parm=="L3.std_lnaid_c"

lab define newlabel -3 "t-3" -2 "t-2" -1 "t-1" 0 "t" 1 "t+1", modify
lab val timevar newlabel

eclplot estimate min90 max90 timevar, eplottype(connected) rplottype(rcap) yscale(range(-3 2)) ylabel(-3(0.5)2) xscale(range(-3 1))  xlabel(-3(1)1, angle(45)) yline(0) xtitle("log(Chinese Aid + 0.01)", size(medsmall)) ytitle("{&Delta} conflict(t)/{&Delta} log(Chinese Aid + 0.01)", size(medsmall)) graphregion( color(white))
graph export "$graphs\lags_leads_china.png", as(png) name("Graph") replace
erase   "$tables\parmest_china.dta"
restore

*******************
* Jack Knife Test *
*******************

eststo clear
* Aid Types:

		drop lnaid
		
foreach a in   AX BX CX EX FX JX LX TX WX YX {
	cap drop std_lnaid 
	cap drop lnaid
	gen lnaid=ln(WBAID_ADM1_LOC-WBAID_ADM1_LOC_`a'+0.01)

	egen std_lnaid=std(lnaid), mean(0)  std(1)

	label var std_lnaid  "Standardized log of location weighted WB aid per capita +0.01"



	* Column (8)
	reghdfe inten1_adm1 $control2 l1.std_lnaid if transaction_year<=2012, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo _`a'
	drop std_lnaid
	drop lnaid

}


coefplot _AX || _BX || _CX || _EX || _FX || _JX || _LX || _TX || _WX || _YX  ///
				, keep(L.std_lnaid) yline(0) bycoefs vertical byopts(yrescale) levels(90) graphregion(color(white)) yscale(range(-0.4 0)) ///
				xtitle(Excluded sectors , color(black) size(large)) xscale(titlegap(3)) ytitle(Coef. and 90% CI, color(black) size(large)) yscale(titlegap(2)) title(WB, color(black) size(large) ) saving("$graphs\sectors_wb", replace)
						estimates drop _all
		
		drop lnaid_c
				foreach a in   AX BX CX EX FX JX LX TX WX YX {
					cap drop lnaid_c 
					cap drop std_lnaid_c
	gen lnaid_c=ln(CAID_ADM1_LOC-CAID_ADM1_LOC_`a'+0.01)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)
	label var std_lnaid_c  "Standardized log of location weighted Chinese aid per capita +0.01"

	* Column (8)
	reghdfe inten1_adm1 $control2 l2.std_lnaid_c if transaction_year>1995, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo _`a'

	drop lnaid_c std_lnaid_c
}
				
				coefplot _AX || _BX || _CX || _EX || _FX || _JX || _LX || _TX || _WX || _YX  ///
				, keep(L2.std_lnaid_c) yline(0) bycoefs vertical byopts(yrescale) levels(90) graphregion(color(white)) yscale(range(-0.4 0)) ///
				xtitle(Excluded sectors, color(black) size(large)) xscale(titlegap(3)) ytitle(Coef. and 90% CI, color(black) size(large)) yscale(titlegap(2)) title(China, color(black) size(large) ) saving("$graphs\sectors_ch", replace)

*				estimates drop _all
				
							graph combine "$graphs\sectors_wb" "$graphs\sectors_ch" , title("", color(black)) scheme(s2mono) graphregion(color(white))  ycommon
							graph export "$graphs\jackknife.png", as(png) name("Graph") replace

* Restore log of total aid and IV for total aid
* Log of aid
gen lnaid=ln(WBAID_ADM1_LOC+0.01)
label var lnaid  "Log of location weighted World Bank Aid per capita +0.01"
gen lnaid_c=ln(CAID_ADM1_LOC+0.01)
label var lnaid_c  "Log of location weighted Chinese Aid per capita +0.01"



**************************************** Coefficient Plots *****************************************************************
********************************************* Actors, Riots, Demonstrations, Strikes and Repression ************************************************************
*Figure 4: Fixed Effects Regressions - Type of Conflict

cap drop std_lnaid std_lnaid_c
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)

global wblag1 			"l1.std_lnaid"
global chinalag2		"l2.std_lnaid_c"

matrix drop _all


// Matrices
mat B=J(7,2,0)
mat C=J(7,2,0)
mat D=J(7,2,0)	
mat E=J(7,2,0)

foreach i in   t1 t2 t3g t3ng {
	cap drop inten1_`i'_adm1
	gen inten1_`i'_adm1=0
	replace inten1_`i'_adm1=100 if brd_`i'_adm1>=5
	}

eststo clear

local no = 1

foreach i in inten1_adm1 inten1_t1_adm1 inten1_t2_adm1 inten1_t3g_adm1 inten1_t3ng_adm1 D_tot_rds_adm1  D_repress_nl {
* Model 1 - state and year FE

	capture 	reghdfe `i' $control2 $wblag1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo `i'_WB1
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'
	

* Model 2 - state, year and region FE
	capture 	reghdfe `i' $control2 $wblag1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo `i'_WB2
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				

// China
* Model 1 - state and year FE

	capture reghdfe `i' $chinalag2 $control2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo `i'_CHINA1
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

* Model 2 - state, year and region FE

	capture reghdfe `i' $chinalag2 $control2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num  i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo `i'_CHINA2
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	
	local no=`no'+1
}

graph set window fontface stSans

coefplot (matrix(B[,1]), se(B[,2]) mcolor("58 85 164") msymbol(o) ciopts(lcolor("58 85 164") lwidth(thin) recast(rcap))  ) (matrix(C[,1]), se(C[,2]) mcolor("58 85 164") msymbol(oh) ciopts(lcolor("58 85 164") lwidth(thin) recast(rcap)) ) 	  , ///
graphregion(color(white))  xline(0, lcolor(grey) lwidth(thin) ) grid(none)  /// 
coeflabels(r1="Outright conflict (OC): >=5 BRD" ///
	r2="OC: State vs. N-state" ///
	r3="OC: N-state vs. N-state" /// 
	r4="OC: State vs. civilians"  /// 
	r5="OC: N-state vs. civilians" ///
	r6="Riots, demonstrations and strikes" ///
	r7="Non-lethal government repression", labsize(small)) /// 
xlabel( , labsize(vsmall))   levels(90)  fxsize(152) xscale(range(-3(1)1)) xlabel(-3(1)1) ///
title("WB", size(small)) ///
legend(on order(2 "Year and region FE" 4 "Country-year and region FE") size(vsmall) col(1) )
graph save "$graphs\wb_type.gph", replace


coefplot (matrix(D[,1]), se(D[,2]) mcolor("212 82 154") msymbol(o) ciopts(lcolor("212 82 154") lwidth(thin) recast(rcap))  ) (matrix(E[,1]), se(E[,2]) mcolor("212 82 154") msymbol(oh) ciopts(lcolor("212 82 154") lwidth(thin) recast(rcap)) ) , ///
graphregion(color(white))  xline(0, lcolor(grey) lwidth(thin) ) grid(none)  ///
xlabel( , labsize(vsmall))  nolabels ylabel(,nolabel)  levels(90)  fxsize(77) xscale(range(-3(1)1)) xlabel(-3(1)1)  /// 
title("China", size(small)) ///
legend(on order(2 "Year and region FE" 4 "Country-year and region FE") size(vsmall) col(1) )

graph save "$graphs\china_type.gph", replace
graph combine "$graphs\wb_type.gph" "$graphs\china_type.gph"  , graphregion(color(white))
graph export "$graphs/coefplot_type_final.pdf", replace 
graph export "$graphs/coefplot_type_final.eps", replace 	
// note: the quality of the png is very bad when the code is executed. I opened the graph editor and save the graph is pdf, which has much better quality and a small file size 

*Coresponding Tables	
			esttab  inten1_t1_adm1_WB1 inten1_t1_adm1_WB2 inten1_t2_adm1_WB1 inten1_t2_adm1_WB2 inten1_t3g_adm1_WB1 inten1_t3g_adm1_WB2 inten1_t3ng_adm1_WB1 inten1_t3ng_adm1_WB2 D_tot_rds_adm1_WB1 D_tot_rds_adm1_WB2  D_repress_nl_WB1 D_repress_nl_WB2 using "$tables/OLS_types_multi_wb_adm1", replace booktabs fragment keep(L.std_lnaid) coeflabels(L.std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-1})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap 

						esttab inten1_t1_adm1_CHINA1 inten1_adm1_CHINA2  inten1_t2_adm1_CHINA1 inten1_t2_adm1_CHINA2 inten1_t3g_adm1_CHINA1 inten1_t3g_adm1_CHINA2 inten1_t3ng_adm1_CHINA1 inten1_t3ng_adm1_CHINA2 D_tot_rds_adm1_CHINA1 D_tot_rds_adm1_CHINA2  D_repress_nl_CHINA1 D_repress_nl_CHINA2 using "$tables/OLS_types_multi_china_adm1", replace booktabs fragment keep(L2.std_lnaid_c) coeflabels(L2.std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap 

*******************************
* Types of Conflict (press)	  *
*******************************
* Figure 23: Results for China Controlled for Press Freedom Interacted With Region FE
foreach z in t1 t2 t3g t3ng { 
	cap drop inten1_`z'_adm1
gen inten1_`z'_adm1=0
replace inten1_`z'_adm1=100 if brd_`z'_adm1>=5 & brd_`z'_adm1!=.
}

eststo clear
mata: mata clear
cap drop std_lnaid std_lnaid_c 
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)

cap drop l1std_lnaid
cap drop l2std_lnaid_c
gen l1std_lnaid=l1.std_lnaid
gen l2std_lnaid_c=l2.std_lnaid_c

global wblag1 			"l1std_lnaid"
global chinalag2		"l2std_lnaid_c"

matrix drop _all

// Matrices
mat B=J(7,2,0)
mat C=J(7,2,0)
mat D=J(7,2,0)	
mat E=J(7,2,0)



local no = 1
			eststo clear
foreach g in inten1_adm1 inten1_t1_adm1 inten1_t2_adm1 inten1_t3g_adm1 inten1_t3ng_adm1 D_tot_rds_adm1  D_repress_nl {
	foreach t in l2std_lnaid_c{
			if "`t'"=="l2std_lnaid_c"{
				* Set endogenous controls with one further lage for Chinese aid as we use commitments with two lags
				global control3 L3.drug_y L3.gem_y  L3.isum_pop_ADM1 L3.goldsurface_y L3.diamprim_y L3.diamsec_y L3.petroleum_y L3.excluded  L3.ln_IBRD_ADM1_LOC L3.lights_sum
						global control_press c.L3.PressFreedom_Score#i.ID_adm1_num
global control_transp c.L3.transparencyindex#i.ID_adm1_num
			}
			if "`t'"=="l1.lnaid"{
				* Set endogenous controls for WB
				global control3 L2.drug_y L2.gem_y  L2.isum_pop_ADM1 L2.goldsurface_y L2.diamprim_y L2.diamsec_y L2.petroleum_y L2.excluded  L2.ln_IBRD_ADM1_LOC L2.lights_sum
						global control_press c.L2.PressFreedom_Score#i.ID_adm1_num
global control_transp c.L2.transparencyindex#i.ID_adm1_num
			}

			

			di "Run regression for dependent variable: `g', treatvar: `t', and cluster level `c'"



			//7. continental trend + country FE + transaction_year Fe + Region FE + D1 and D3  + endogenous controls quadratic country trend + region trend
			reghdfe `g' `t' $control2 $control3  , cluster(fcy fr) absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend) // $control_press
		capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'


						//9. continental trend + country FE + transaction_year Fe + Region FE + D1 and D3 + continental trend + quadratic country trend + region trend + Country-Transaction_year FE  + endogeneous controls
			quietly reghdfe `g' `t' $control2 $control3,    cluster(fcy fr) absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend i.state#i.transaction_year) // $control_press,
		capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'	
	
	
				//7. continental trend + country FE + transaction_year Fe + Region FE + D1 and D3  + endogenous controls quadratic country trend + region trend
			reghdfe `g' `t' $control2 $control3  $control_press, cluster(fcy fr) absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend) // 
		capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'


						//9. continental trend + country FE + transaction_year Fe + Region FE + D1 and D3 + continental trend + quadratic country trend + region trend + Country-Transaction_year FE  + endogeneous controls
			quietly reghdfe `g' `t' $control2 $control3 $control_press,   cluster(fcy fr) absorb(i.continent_num#i.transaction_year i.state i.transaction_year i.ID_adm1_num i.state#c.trend i.state#c.trend_sq i.ID_adm1_num#c.trend i.state#i.transaction_year) // 
		capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	


		local no=`no'+1
		}
	}

	
	coefplot (matrix(B[,1]), se(B[,2]) mcolor("58 85 164") msymbol(o) msize(small) ciopts(lcolor("58 85 164") lwidth(thin) recast(rcap))  ) (matrix(C[,1]), se(C[,2]) mcolor("58 85 164") msymbol(oh) msize(small) ciopts(lcolor("58 85 164") lwidth(thin) recast(rcap)) ) 	  , ///
graphregion(color(white))  xline(0, lcolor(grey) lwidth(vthin) ) grid(none)  /// 
coeflabels(r1="Outright conflict (OC): >=5 BRD" ///
	r2="OC: State vs. N-state" ///
	r3="OC: N-state vs. N-state" /// 
	r4="OC: State vs. civilians"  /// 
	r5="OC: N-state vs. civilians" ///
	r6="Riots, demonstrations and strikes" ///
	r7="Non-lethal government repression", labsize(small) ) ///
	xlabel( , labsize(small))   levels(90)  fxsize(132)  ///
title("Baseline", size(small)) ///
legend(on order(2 "Year and region FE" 4 "County-year and region FE") size(vsmall) col(1) ) xscale(range(-1(1)1.5)) xlabel(-1(1)1.5) 
graph save "$graphs\china_no_press.gph", replace


	coefplot (matrix(D[,1]), se(D[,2]) mcolor("58 85 164") msymbol(o) msize(small) ciopts(lcolor("58 85 164") lwidth(thin) recast(rcap))  ) (matrix(E[,1]), se(E[,2]) mcolor("58 80 64") msymbol(oh) msize(small) ciopts(lcolor("58 80 64") lwidth(thin) recast(rcap)) ) 	  , ///
graphregion(color(white))  xline(0, lcolor(grey) lwidth(vthin) ) grid(none)  /// 
coeflabels(r1=" " ///
	r2=" " ///
	r3=" " /// 
	r4=" "  /// 
	r5=" " ///
	r6=" " ///
	r7=" ", labsize(small) ) ///
	xlabel( , labsize(small))   levels(90)  fxsize(82)  ///
title("Control for Press Freedom", size(small)) ///
legend(on order(2 "Year and region FE" 4 "County-year and region FE") size(vsmall) col(1) ) xscale(range(-1(1)1.5)) xlabel(-1(1)1.5) 
graph save "$graphs\china_press.gph", replace
graph combine "$graphs\china_no_press.gph" "$graphs\china_press.gph"  , graphregion(color(white))
graph export "$graphs/coefplot_press_comparison.pdf", as(pdf) replace 
graph export "$graphs/coefplot_press_comparison.eps", replace 	


*/
*******************************
* Robustness Coeff Plot 	  *
*******************************
eststo clear
mata: mata clear
cap drop std_lnaid std_lnaid_c 
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)

cap drop l1std_lnaid l2std_lnaid_c
gen l1std_lnaid=l1.std_lnaid
gen l2std_lnaid_c=l2.std_lnaid_c

global wblag1 			"l1std_lnaid"
global chinalag2		"l2std_lnaid_c"

matrix drop _all

// Matrices
mat B=J(24,2,0)
mat C=J(24,2,0)
mat D=J(24,2,0)	
mat E=J(24,2,0)

* Gen new brd measure
gen brd_adm1_cont=brd_adm1/33417*100
gen asinhbrd_adm1=asinh(brd_adm1)
egen std_lnbrd=std(lnbrd_adm1), mean(0)  std(1)
egen std_brd=std(brd_adm1), mean(0)  std(1)

local no = 1

	* 1) Other outcomes
foreach i in inten1_adm1 inten2_adm1  asinhbrd_adm1  { // lnbrd_adm1

		reghdfe `i' $control2 $wblag1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
		eststo `i'_WB1
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'

* Model 2 - state, year and region FE
		reghdfe `i' $control2 $wblag1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
		eststo `i'_WB2
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				

// China
* Model 1 - state and year FE

	 reghdfe `i' $control2 $chinalag2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo `i'_CHINA1
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

* Model 2 - state, year and region FE

	reghdfe `i' $control2 $chinalag2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo `i'_CHINA2
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	
	local no=`no'+1
}

	* 2) Other treatment
	* a) population weighted aid
cap drop std_lnaid std_lnaid_c l1std_lnaid l2std_lnaid_c
egen std_lnaid=std(ln(WBAID_ADM1_POP+0.01)), mean(0)  std(1)
egen std_lnaid_c=std(ln(CAID_ADM1_POP+0.01)), mean(0)  std(1)

gen l1std_lnaid=l1.std_lnaid
gen l2std_lnaid_c=l2.std_lnaid_c

global wblag1 			"l1std_lnaid"
global chinalag2		"l2std_lnaid_c"

	capture reghdfe inten1_adm1 $control2 $wblag1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
		eststo pop_WB1
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'

* Model 2 - state, year and region FE
	capture reghdfe inten1_adm1 $control2 $wblag1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo pop_WB2
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				

// China
* Model 1 - state and year FE

	capture reghdfe inten1_adm1 $control2 $chinalag2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo pop_CHINA1
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

* Model 2 - state, year and region FE

	capture reghdfe inten1_adm1 $control2 $chinalag2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo pop_CHINA2
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	
	local no=`no'+1
	
	* b) asinh
	cap drop std_lnaid std_lnaid_c l1std_lnaid l2std_lnaid_c
	egen std_lnaid=std(asinh(WBAID_ADM1_LOC)), mean(0)  std(1)
	egen std_lnaid_c=std(asinh(CAID_ADM1_LOC)), mean(0)  std(1)

gen l1std_lnaid=l1.std_lnaid
gen l2std_lnaid_c=l2.std_lnaid_c

global wblag1 			"l1std_lnaid"
global chinalag2		"l2std_lnaid_c"

// wb
* Model 1 - state and year FE
		capture reghdfe inten1_adm1 $control2 $wblag1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
		eststo asinhaid_WB1
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'

* Model 2 - state, year and region FE
	capture reghdfe inten1_adm1 $control2 $wblag1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo asinhaid_WB2
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				

// China
* Model 1 - state and year FE

	capture reghdfe inten1_adm1 $control2 $chinalag2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo asinhaid_CHINA1
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

* Model 2 - state, year and region FE

	capture reghdfe inten1_adm1 $control2 $chinalag2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo asinhaid_CHINA2
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	
	local no=`no'+1

* 3) Press Freedom

// World Bank
* Model 1 - state and year FE
	capture reghdfe inten1_adm1 $control2 $wblag1 c.L2.PressFreedom_Score#i.ID_adm1_num , absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo press_WB1
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'

* Model 2 - state, year and region FE
	capture 	reghdfe inten1_adm1 $control2 $wblag1 c.L2.PressFreedom_Score#i.ID_adm1_num , absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo press_WB2
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				

	
// China
* Model 1 - state and year FE
	capture reghdfe inten1_adm1 $control2 $chinalag2 c.L3.PressFreedom_Score#i.ID_adm1_num, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.transaction_year i.state i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo press_CHINA1
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

* Model 2 - state, year and region FE

	capture  reghdfe inten1_adm1 $control2 $chinalag2  c.L3.PressFreedom_Score#i.ID_adm1_num, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo press_CHINA2
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	
	local no=`no'+1
	
	* 4) Control for pre-trends
gen l1std_lnaid_c=l1.std_lnaid_c

		reghdfe inten1_adm1 $control2 $wblag1 std_lnaid, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo pretrend_WB1


	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'

* Model 2 - state, year and region FE
		reghdfe inten1_adm1 $control2 $wblag1 std_lnaid, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo pretrend_WB2
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				

// China
* Model 1 - state and year FE

	 reghdfe inten1_adm1 $control2 $chinalag2 l1std_lnaid_c, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo pretrend_CHINA1
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

* Model 2 - state, year and region FE

	reghdfe inten1_adm1 $control2 $chinalag2 l1std_lnaid_c, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo pretrend_CHINA2
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	
	local no=`no'+1
	
	* 5) Lagged dependent variable

// WB
* Model 1 - state and year FE
	 	reghdfe inten1_adm1 $control2 $wblag1 l1.inten1_adm1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo lagdep_WB1
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'

* Model 2 - state, year and region FE
		reghdfe inten1_adm1 $control2 $wblag1 l1.inten1_adm1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo lagdep_WB2
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				

// China
* Model 1 - state and year FE

	capture reghdfe inten1_adm1 $control2 $chinalag2 l1.inten1_adm1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo lagdep_CHINA1
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

* Model 2 - state, year and region FE

	capture reghdfe inten1_adm1 $control2 $chinalag2 l1.inten1_adm1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo lagdep_CHINA2
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	
	local no=`no'+1
	
* 6) Leader birth region, lights, powerless populations
	// World Bank
* Model 1 - state and year FE
	capture reghdfe inten1_adm1 $control2 $wblag1  l2.birthregion l2.lights_sum l2.share_powerless, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo loc_selec_WB1
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'

* Model 2 - state, year and region FE
	capture 	reghdfe inten1_adm1 $control2 $wblag1  l2.birthregion l2.lights_sum l2.share_powerless, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo loc_selec_WB2
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				

	
// China
* Model 1 - state and year FE
	capture reghdfe inten1_adm1 $control2 $chinalag2 l3.birthregion l3.lights_sum l3.share_powerless, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.transaction_year i.state i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo loc_selec_CHINA1
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

* Model 2 - state, year and region FE

	capture  reghdfe inten1_adm1 $control2 $chinalag2  l3.birthregion l3.lights_sum l3.share_powerless, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo loc_selec_CHINA2
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	
	local no=`no'+1

	
	
* 7) Both donors
cap drop std_lnaid std_lnaid_c l1std_lnaid l2std_lnaid_c
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)

gen l1std_lnaid=l1.std_lnaid
gen l2std_lnaid_c=l2.std_lnaid_c

global wblag1 			"l1std_lnaid"
global chinalag2		"l2std_lnaid_c"

		 reghdfe inten1_adm1 $control2 $wblag1 $chinalag2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
		eststo bothdon_WB1
		eststo bothdon_CHINA1
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'
	
		capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

* Model 2 - state, year and region FE
	capture	reghdfe inten1_adm1 $control2 $wblag1 $chinalag2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo bothdon_WB2
	eststo bothdon_CHINA2
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'
	
		capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	


	local no=`no'+1
	di `no' 
	
	
	
	
	* 8) Clustering
foreach cluster in fr fc fcy {
	// WB
* Model 1 - state and year FE
	capture reghdfe inten1_adm1 $control2 $wblag1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.`cluster')
	eststo cluster_`cluster'_WB1
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'

* Model 2 - state, year and region FE
	capture reghdfe inten1_adm1 $control2 $wblag1, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.`cluster')
	eststo cluster_`cluster'_WB2
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				

// China
* Model 1 - state and year FE
	capture reghdfe inten1_adm1 $control2 $chinalag2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.`cluster')
	eststo cluster_`cluster'_CHINA1
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

* Model 2 - state, year and region FE

	capture reghdfe inten1_adm1 $control2 $chinalag2, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.`cluster')
	eststo cluster_`cluster'_CHINA2
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	
	local no=`no'+1
}


*  9) ********************** ADM2 ***************************************************************
preserve
***********************
* Analysis ADM2 Level *
***********************
*eststo clear
use "$data\Merge\IDA_Aid_GED_ADM2.dta", clear

* keep only African dataset
keep if unregion2=="Africa"

// drop small economies and islands
drop if d_smallcountry ==1

* Generate continental identifiers
egen continent_num=group(unregion2)

* Aid data
gen lnaid=ln(WBAID_ADM2_LOC+0.01)
label var lnaid  "Log of population weighted World Bank Aid per capita +0.01"
gen lnaid_c=ln(CAID_ADM2_LOC+0.01)
label var lnaid_c  "Log of population weighted Chinese Aid per capita +0.01"

* Conflict Data
* Genreate new intensity thresholds
gen inten1_adm2=0
replace inten1_adm2=100 if brd_adm2>=5

gen inten2_adm2=0
replace inten2_adm2=100 if brd_adm2>=25

* Generate Latitude and Longitude for time-interaction
gen lon=abs(xcoord)
gen lat=abs(ycoord)

sort ID_adm2_num transaction_year
bysort ID_adm2_num: egen mean_temp=mean(temp)
egen trend=group(transaction_year)
gen trend_sq=trend*trend
gen trend_cub=trend*trend*trend



* Set Chinese aid to missing for non-African states and year<2000 & years>2012
replace lnaid_c=. if unregion2!="Africa" | transaction_year<2000 | transaction_year>2012

***************
* Globals for *
* Regressions *
***************
xtset ID_adm2_num transaction_year
* Set controls
global control2 droughtend_spi droughtstart_spi temp prec_gpcc c.ttime_mean#i.transaction_year  c.landarea#i.transaction_year  c.dist_capital#i.transaction_year c.mean_temp#i.transaction_year c.elevation_std#i.transaction_year c.Dborder#i.transaction_year c.Driver#i.transaction_year c.Dlake#i.transaction_year c.Docean#i.transaction_year c.lat#i.transaction_year c.lon#i.transaction_year
* Standardize treatment
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)

gen l1std_lnaid=l1.std_lnaid
gen l2std_lnaid_c=l2.std_lnaid_c

global wblag1 			"l1std_lnaid"
global chinalag2		"l2std_lnaid_c"

*Labeling
global ln "$\ln" 


	reghdfe inten1_adm2 $control2 $wblag1, absorb(i.ID_adm2_num#c.trend i.ID_adm2_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm2_num)
	eststo ADM2_WB1
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'

* Model 2 - state, year and region FE
	capture 	reghdfe inten1_adm2 $control2 $wblag1, absorb(i.ID_adm2_num#c.trend i.ID_adm2_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm2_num)
	eststo ADM2_WB2
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				

// China
* Model 1 - state and year FE

	reghdfe inten1_adm2 $control2  $chinalag2, absorb(i.ID_adm2_num#c.trend i.ID_adm2_num i.state i.transaction_year i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm2_num)
	eststo ADM2_CHINA1
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

* Model 2 - state, year and region FE

	capture reghdfe inten1_adm2 $control2  $chinalag2, absorb(i.ID_adm2_num#c.trend i.ID_adm2_num  i.transaction_year#i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm2_num)
	eststo ADM2_CHINA2
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	
	local no=`no'+1
restore

	* 10) Non-linear estimators
*eststo clear
cap drop std_lnaid std_lnaid_c l1std_lnaid l2std_lnaid_c
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)

gen l1std_lnaid=l1.std_lnaid
gen l2std_lnaid_c=l2.std_lnaid_c

global wblag1 			"l1std_lnaid"
global chinalag2		"l2std_lnaid_c"
	
	* Gen year dummies
forval i = 1995(1)2014 {
	gen fy`i'=0
	replace fy`i'=1 if transaction_year==`i'
}

foreach var in inten1_adm1 {
* XTNBREG
*WB
xtset ID_adm1_num transaction_year
xtnbreg `var' $wblag1  fy*, fe 
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'

* China
xtnbreg `var' $chinalag2 fy*, fe  
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

		local no=`no'+1

* Poisson
* WB
xtpqml `var' $wblag1 fy*	, i(ID_adm1_num) cluster(ID_adm1_num) 
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'

* China
xtpqml `var' $chinalag2 fy*, i(ID_adm1_num) cluster(ID_adm1_num) 
capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'

	local no=`no'+1
}

************* Channels
* 11-12) Fractionalization & power stati
	foreach var in L_frac group_coalition { 
			forvalues a=0(1)1 {
	reghdfe inten1_adm1 $control2 $wblag1 if `var'==`a' & epr_low_var==0, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'
	reghdfe inten1_adm1 $control2 l1.std_lnaid if `var'==`a' & epr_low_var==0, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo `var'_WB1_`a'


* Model 2 - state, year and region FE
	reghdfe inten1_adm1 $control2 $wblag1 if `var'==`a' & epr_low_var==0, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'
	reghdfe inten1_adm1 $control2 l1.std_lnaid if `var'==`a' & epr_low_var==0, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo `var'_WB2_`a'


// China
* Model 1 - state and year FE

	reghdfe inten1_adm1 $control2 $chinalag2 if `var'==`a' & epr_low_var==0, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'
	reghdfe inten1_adm1 $control2 l2.std_lnaid_c if `var'==`a' & epr_low_var==0, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo `var'_CHINA1_`a'

* Model 2 - state, year and region FE

	reghdfe inten1_adm1 $control2 $chinalag2 if `var'==`a' & epr_low_var==0, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	local no=`no'+1
	reghdfe inten1_adm1 $control2 l2.std_lnaid_c if `var'==`a' & epr_low_var==0, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo `var'_CHINA2_`a'

	}
	}
	
* 13) Democracy (Bjornskov & Rode)
	foreach var in democracy_br { 
			forvalues a=0(1)1 {
	reghdfe inten1_adm1 $control2 $wblag1 if `var'==`a', absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'
	reghdfe inten1_adm1 $control2 l.std_lnaid if `var'==`a', absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo DEMO_WB1_`a'


* Model 2 - state, year and region FE
	reghdfe inten1_adm1 $control2 $wblag1 if `var'==`a', absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				
	reghdfe inten1_adm1 $control2 l.std_lnaid if `var'==`a', absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo DEMO_WB2_`a'

// China
* Model 1 - state and year FE
	reghdfe inten1_adm1 $control2 $chinalag2 if `var'==`a', absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'
	reghdfe inten1_adm1 $control2 l2.std_lnaid_c if `var'==`a', absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo DEMO_CHINA1_`a'

* Model 2 - state, year and region FE

	reghdfe inten1_adm1 $control2 $chinalag2 if `var'==`a', absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	local no=`no'+1
	reghdfe inten1_adm1 $control2 l2.std_lnaid_c if `var'==`a', absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo DEMO_CHINA2_`a'

	}
	}
	
local no=23	
* 14) Temporal split
* First half *
* Model 1 - state, year and region FE
	reghdfe inten1_adm1 $control2 $wblag1 if transaction_year<=2004, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'
		reghdfe inten1_adm1 $control2 l1.std_lnaid if transaction_year<=2004, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo FIRST_WB1


* Model 2 - state-year and region FE
	reghdfe inten1_adm1 $control2 $wblag1 if transaction_year<=2004, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				
		reghdfe inten1_adm1 $control2 l1.std_lnaid if transaction_year<=2004, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo FIRST_WB2

// China
* Model 1 - state, year and region FE
	reghdfe inten1_adm1 $control2 $chinalag2 if transaction_year<=2007, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'
	reghdfe inten1_adm1 $control2 l2.std_lnaid_c if transaction_year<=2007, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo FIRST_CHINA1

* Model 2 - state-year and region FE

	reghdfe inten1_adm1 $control2 $chinalag2 if transaction_year<=2007, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	reghdfe inten1_adm1 $control2 l2.std_lnaid_c if transaction_year<=2007, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo FIRST_CHINA2
	
	local no=`no'+1

* Second Half of Years
	reghdfe inten1_adm1 $control2 $wblag1 if transaction_year>2004, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'
		reghdfe inten1_adm1 $control2 l1.std_lnaid if transaction_year>2004, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo SECOND_WB1


* Model 2 - state, year and region FE
	reghdfe inten1_adm1 $control2 $wblag1 if transaction_year>2004, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				
		reghdfe inten1_adm1 $control2 l1.std_lnaid if transaction_year>2004, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo SECOND_WB2

// China
* Model 1 - state and year FE
	reghdfe inten1_adm1 $control2 $chinalag2 if transaction_year>2007, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'
	reghdfe inten1_adm1 $control2 l2.std_lnaid_c if transaction_year>2007, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo SECOND_CHINA1

* Model 2 - state, year and region FE

	reghdfe inten1_adm1 $control2 $chinalag2 if transaction_year>2007, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'	
	reghdfe inten1_adm1 $control2 l2.std_lnaid_c if transaction_year>2007, absorb(i.ID_adm1_num#c.trend i.ID_adm1_num i.state#i.transaction_year  i.state#c.trend i.state#c.trend_sq) cluster(i.state#i.transaction_year i.ID_adm1_num)
	eststo SECOND_CHINA2
	


* Set other fixed effects results to missing
matrix C[15, 1] =.
matrix C[15, 2] =.
matrix C[16, 1] =.
matrix C[16, 2] =.

matrix E[15, 1] =.
matrix E[15, 2] =.
matrix E[16, 1] =.
matrix E[16, 2] =.


graph set window fontface stSans




coefplot (matrix(B[,1]), se(B[,2]) mcolor("58 85 164") msymbol(o) msize(small) ciopts(lcolor("58 85 164") lwidth(thin) recast(rcap))  ) (matrix(C[,1]), se(C[,2]) mcolor("58 85 164") msymbol(oh) msize(small) ciopts(lcolor("58 85 164") lwidth(thin) recast(rcap)) ) 	  , ///
graphregion(color(white))  xline(0, lcolor(grey) lwidth(vthin) ) grid(none)  /// 
coeflabels(r1="Conflict threshold BRD>=5" ///
	r2="Conflict threshold BRD>=25" ///
	r3="Inverse hyperbolic sine of BRD" ///
	r4="Population-weighted aid" ///
	r5="Inverse hyperbolic sine of aid" ///
	r6="Control for press freedom" ///
	r7="Control for pre-trends" ///
	r8="Lagged dependent variable" ///
	r9="Control for other selection concerns" ///
	r10="Both donors" ///
	r11="Regional clustering" ///
	r12="Country-year clustering" ///
	r13="Country clustering" ///
	r14="Aggregation level: ADM2" ///
	r15="Negative binomial" ///
	r16="Poisson" ///
		r17="Low ethnic fractionalization" ///
	r18="High ethnic fractionalization" ///
	r19="Coalition: excluded" ///
	r20="Coalition: included" ///
	r21="Autocracy" ///
	r22="Democracy" ///
	r23="First half of sampling period" ///
	r24="Second half of sampling period", labsize(small) ) ///
	headings(r1 = "{bf: Panel A: Outcome and treatment measurement}"                     ///
	r6 = "{bf: Panel B: Selection on the local level}"                        ///
	r11 = "{bf: Panel C: Clustering}"                        ///
	r14= "{bf: Panel D: Modifiable area unit problem}" ///
	r15= "{bf: Panel E: Alternative estimators}" ///
	r17= "{bf: Panel F: Heterogeneity}", labsize(small) ) ///
	xlabel( , labsize(small))   levels(90)  fxsize(157)  ///
title("WB", size(small)) ///
legend(on order(2 "Year and region FE" 4 "County-year and region FE") size(vsmall) col(1) ) xscale(range(-5(2)2)) xlabel(-4(2)2) 
graph save "$graphs\wb_robustness.gph", replace



coefplot (matrix(D[,1]), se(D[,2]) mcolor("212 82 154") msymbol(o)  msize(small) ciopts(lcolor("212 82 154") lwidth(thin) recast(rcap))  ) (matrix(E[,1]), se(E[,2]) mcolor("212 82 154") msymbol(oh)  msize(small) ciopts(lcolor("212 82 154") lwidth(thin) recast(rcap)) ) , ///
graphregion(color(white))  xline(0, lcolor(grey) lwidth(thin) ) grid(none)  ///
	headings(r1 = " "                     ///
	r6 = " "                        ///
	r11 = " "                        ///
	r14= " " ///
	r15=" " ///
	r17=" ") ///
xlabel( , labsize(small))  nolabels ylabel(,nolabel)  levels(90)  fxsize(71)  /// 
title("China", size(small)) xscale(range(-5(2)2)) xlabel(-4(2)2) /// 
legend(on order(2 "Year and region FE" 4 "Country-year and region FE") size(vsmall) col(1) )

graph save "$graphs/china_robustness.gph", replace
graph combine "$graphs/wb_robustness.gph" "$graphs/china_robustness.gph"  , graphregion(color(white))
graph export "$graphs/coefplot_robustness_final.png", as(png) replace 
graph export "$graphs/coefplot_robustness_final.eps", replace 	
graph export "$graphs/coefplot_robustness_final.pdf", replace 	

// note: the quality of the png is very bad when the code is executed. I opened the graph editor and save the graph as pdf, which has much better quality and a small file size 


*Table 22: FE – Outcome and Treatment Measurement
			esttab inten1_adm1_WB1 inten1_adm1_WB2 inten2_adm1_WB1 inten2_adm1_WB2   asinhbrd_adm1_WB1 asinhbrd_adm1_WB2 pop_WB1 pop_WB2 asinhaid_WB1 asinhaid_WB2 using "$tables/OLS_sens1_multi_wb_adm1", replace booktabs fragment keep(l1std_lnaid) coeflabels(l1std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-1})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap // lnbrd_adm1_WB1 lnbrd_adm1_WB2

						esttab inten1_adm1_CHINA1 inten1_adm1_CHINA2 inten2_adm1_CHINA1 inten2_adm1_CHINA2  asinhbrd_adm1_CHINA1 asinhbrd_adm1_CHINA2 pop_CHINA1 pop_CHINA2 asinhaid_CHINA1 asinhaid_CHINA2 using "$tables/OLS_sens1_multi_china_adm1", replace booktabs fragment keep(l2std_lnaid_c) coeflabels(l2std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap // lnbrd_adm1_CHINA1 lnbrd_adm1_CHINA2

			
			
*Table 23: Table 23: FE – Selection Concerns
			esttab press_WB1 press_WB2 pretrend_WB1 pretrend_WB2 lagdep_WB1 lagdep_WB2 loc_selec_WB1 loc_selec_WB2 bothdon_WB1 bothdon_WB2 using "$tables/OLS_sens2_multi_wb_adm1", replace booktabs fragment keep(l1std_lnaid) coeflabels(l1std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-1})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap 

						esttab press_CHINA1 press_CHINA2 pretrend_CHINA1 pretrend_CHINA2 lagdep_CHINA1 lagdep_CHINA2 loc_selec_CHINA1 loc_selec_CHINA2 bothdon_CHINA1 bothdon_CHINA2 using "$tables/OLS_sens2_multi_china_adm1", replace booktabs fragment keep(l2std_lnaid_c ) coeflabels(l2std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap 
			
			
* Table 24: FE – Different Clustering Approaches
			esttab cluster_fr_WB1 cluster_fr_WB2 cluster_fcy_WB1 cluster_fcy_WB2  cluster_fc_WB1 cluster_fc_WB2  using "$tables/OLS_sens3_multi_wb_adm1", replace booktabs fragment keep(l1std_lnaid) coeflabels(l1std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-1})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap 

						esttab cluster_fr_CHINA1 cluster_fr_CHINA2  cluster_fcy_CHINA1 cluster_fcy_CHINA2 cluster_fc_CHINA1 cluster_fc_CHINA2  using "$tables/OLS_sens3_multi_china_adm1", replace booktabs fragment keep(l2std_lnaid_c) coeflabels(l2std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap 
			
* Table 25: FE – Modifiable Area Unit Problem – ADM2
			esttab ADM2_WB1 ADM2_WB2 using "$tables/OLS_sens4_multi_wb_adm1", replace booktabs fragment keep(l1std_lnaid) coeflabels(l1std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-1})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap 

						esttab ADM2_CHINA1 ADM2_CHINA2 using "$tables/OLS_sens4_multi_china_adm1", replace booktabs fragment keep(l2std_lnaid_c ) coeflabels(l2std_lnaid_c  "$ln(Chinese\,Aid\,\textsubscript{t-2})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap			


* Table 27: FE - Heterogeneity – 1/2
			esttab L_frac_WB1_0 L_frac_WB2_0  L_frac_WB1_1 L_frac_WB2_1 group_coalition_WB1_0 group_coalition_WB2_0  group_coalition_WB1_1 group_coalition_WB2_1 using "$tables/OLS_channels1_multi_wb_adm1", replace booktabs fragment keep(L.std_lnaid) coeflabels(L.std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-1})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap 

						esttab  L_frac_CHINA1_0 L_frac_CHINA2_0  L_frac_CHINA1_1 L_frac_CHINA2_1 group_coalition_CHINA1_0 group_coalition_CHINA2_0  group_coalition_CHINA1_1 group_coalition_CHINA2_1 using "$tables/OLS_channels1_multi_china_adm1", replace booktabs fragment keep(L2.std_lnaid_c) coeflabels(L2.std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$") ///
			se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap 

			
* Table 28: FE - Heterogeneity – 2/2
esttab DEMO_WB1_0 DEMO_WB2_0 DEMO_WB1_1 DEMO_WB2_1 FIRST_WB1 FIRST_WB2  SECOND_WB1 SECOND_WB2  using "$tables/OLS_channels2_multi_wb_adm1", replace booktabs fragment keep(L.std_lnaid) coeflabels(L.std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-1})$") ///
se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap 

esttab DEMO_CHINA1_0 DEMO_CHINA2_0 DEMO_CHINA1_1 DEMO_CHINA2_1 FIRST_CHINA1 FIRST_CHINA2  SECOND_CHINA1 SECOND_CHINA2 using "$tables/OLS_channels2_multi_china_adm1", replace booktabs fragment keep(L2.std_lnaid_c) coeflabels(L2.std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$") ///
se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress    nomtitles parentheses obslast nonumbers noline nogap 


***********************
* Non-linear Models   *
***********************
use "$data\working_file.dta", clear

*Table 26: Negative Binomial and Poisson
*Standard Deviation as Treatment
			cap drop std_lnaid std_lnaid_c l1std_lnaid l2std_lnaid_c
				egen std_lnaid=std(lnaid), mean(0)  std(1)
			egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)
* Need to define lags manually to work with regression commands
			gen l1std_lnaid=l1.std_lnaid_c
			gen l2std_lnaid_c=l2.std_lnaid_c
			
global wblag1 			"l1std_lnaid"
global chinalag2		"l2std_lnaid_c"
	
* Gen year dummies
xtset ID_adm1_num transaction_year



	* Gen year dummies
forval i = 1995(1)2014 {
	gen fy`i'=0
	replace fy`i'=1 if transaction_year==`i'
}

* XTNBREG & Poisson
*WB
eststo clear
xtset ID_adm1_num transaction_year
xtnbreg inten1_adm1 $wblag1  fy*, fe
eststo xtnbreg_wb1
xtpqml inten1_adm1 $wblag1 fy*	, i(ID_adm1_num) cluster(ID_adm1_num) 
eststo ppml_wb1
esttab xtnbreg_wb1 ppml_wb1 using "$tables\xtnbreg_ppml_wb.tex", replace booktabs fragment keep(l1std_lnaid) ///
coeflabels(l1std_lnaid "$ln(World\,Bank\,Aid\,\textsubscript{t-1})$") se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress   ///
mtitles("" "Neg. Binomial" "PPML" ) parentheses r2 nonumbers noline nogap  obslast nodepvar

* China
xtnbreg inten1_adm1 $chinalag2 fy*, fe  
eststo xtnbreg_china1
xtpqml inten1_adm1 $chinalag2 fy*, i(ID_adm1_num) cluster(ID_adm1_num) 
eststo ppml_china1
esttab xtnbreg_china1 ppml_china1 using "$tables\xtnbreg_ppml_china.tex", replace booktabs fragment keep(l2std_lnaid_c) ///
coeflabels(l2std_lnaid_c "$ln(Chinese\,Aid\,\textsubscript{t-2})$") se star(* 0.10 ** 0.05 *** 0.01) b(%9.4f) compress   ///
mtitles("Neg. Binomial" "PPML" ) parentheses r2 nonumbers noline nogap  obslast nodepvar


******************************************************
*ADO write_mats from alemartinello - GitHub
******************************************************
program define write_mats
	syntax namelist (max=3) using [, names(string) STARs(namelist min=2 max=2) PARentheses(string) ///
	NDecimals(integer 3) append(namelist max=1) appendnames(string) space(real 0.5)]
	
	* name beta and serr matrix as first and second matrix of namelist "stars"
	if "`stars'"!="" gettoken beta serr : stars
	* checks nr and nc
	local count = 1
	foreach mat in `namelist' `stars' {
		if `count'==1 {
			local nc = colsof(`mat')
			local nr = rowsof(`mat')
		}
		else{
			if `nc'!=colsof(`mat') | `nr'!=rowsof(`mat') {
				di as error "Matrix dimensions do not match"
				exit
			}
		}
	}
	if "`append'"!=""{
		if `nc'!=colsof(`append') {
			di as error "Matrix dimensions do not match"
			exit	
		}
	}
	
	if "`parentheses'"=="" local parentheses "() []"
	tokenize `parentheses'
	local np = wordcount("`parentheses'")
	forval i=1/`np' {
		local cp = `i'+1
		local paro`cp' = substr("``i''",1,1)
		local parc`cp' = substr("``i''",2,2) 
	}
	
	local nm = wordcount("`namelist'")
		
	file open table `using', write text replace
	forval i=1/`nr' {
		
		*label row
		if `"`names'"'!="" gettoken lab names: names
		else local lab `i'
		file write table "`lab'" _tab
		
		forval v=1/`nm' {
			* get name of matrix
			local vec=word("`namelist'",`v')
			forval j=1/`nc' {
				if "`stars'"!="" & "`vec'"=="`beta'" {
					local z = normal(abs((`beta'[`i',`j'])/(`serr'[`i',`j'])))
					if `z'>0.995 local st "$^{**}$ " 
					else if `z'>0.975 local st "$^{*}$  "
					else if `z'>0.95 local st "$^{+}$  "
					else local st "   " 
				}
				else local st "   "
				
				if `v'==1 local paro " "
				else if `v'==2 local paro "`paro2'"
				else if `v'==3 local paro "`paro3'"
				
				if `v'==1 local parc ""
				else if `v'==2 local parc "`parc2'"
				else if `v'==3 local parc "`parc3'"
				
				local towrite = string(`vec'[`i',`j'],"%9.`ndecimals'f")
				if (`vec'[`i',`j']) != . {
					file write table "&" "`paro'`towrite'`parc'""`st'"
				}
				else {
					file write table "&"
				}
			}
			if `v'==`nm' & `i'!=`nr' file write table " \\" _newline "[`space'em]" _newline
			else file write table " \\" _newline _tab
		}
		
	}
	if "`append'"!="" {
		file write table "\midrule" _newline
		local nr = rowsof(`append')
		forval i=1/`nr' {
			
			*label row
			if `"`appendnames'"'!="" gettoken lab appendnames: appendnames
			else local lab `i'
			file write table "`lab'" _tab
			forval j=1/`nc' {
				// To avoid reporting .000 for number of observations
				if `append'[`i',`j']>999 local revised_ndecimal 0
				else local revised_ndecimal `ndecimals'
				if `append'[`i',`j']!=. file write table "& " %12.`revised_ndecimal'f (`append'[`i',`j']) "     "
				else file write table "& "
			}
		file write table " \\" _newline
		}
	}
	
	
	file close table
	
end

***************************
*  Analysis Afrobarometer *
***************************
**# Bookmark #1

* Open Data
use "$data\Merge\afb_all_rounds_georef_conflict_merged.dta" , clear
keep if unregion2=="Africa"

// drop small economies and islands
drop if d_smallcountry ==1
* Set Chinese aid to missing for non-African states and year<2000 & years>2012
replace lnaid_c=. if unregion2!="Africa" | transaction_year<2000 | transaction_year>2012

*reverse variable on banning organizations
replace q16_x=-q16_x
replace q16_x=q16_x+5 //Now means opposition to banning organizations


***************
* Globals for *
* Regressions *
***************
xtset ID_adm1_num transaction_year

*Labeling
global ln "\$ln"
xtset ID_adm1_num transaction_year
*Locals
local DepVar q4a q4b q5 q6 q7 q7b q8a q8b q8c q8d q28a q28b q28c  q40 q41 q42a q42b ///
q52a q52b q52c q52e q52f q52g q52h q52i q52j q88a  q10a_x q11a_x q11b_x q13_x q15a_x ///
q15b_x q15c_x q16_x q20b_x q22_x q30_x q24c_x q49_x q51a_x //  q52k 



*****************************************************************************************************************
**************Create matrices with results *********************************************************************
*****************************************************************************************************************

* Table 21: Mechanisms - Afrobarometer

* Table in paper: "ADM1  OLS results (Aid and Conflict at the Local Level)" 
local DepVar  q7b	q4b	q8a	q8b	q8c	q8d			ea_fac_c	ea_sec_a	ea_sec_b	q11a_x	q11b_x			q40	q22_x	q28a	q28b	q28c	q16_x			q24c_x	q49_x		q51a_x	q42b q27a


* Panel A: General effects on economy/percieved income effect
local panelA_long q7b q4b	q8a	q8b	q8c	q8d
quietly{
	eststo clear
	foreach g in `panelA_long'{
		capture reghdfe `g' l1.lnaid, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year)
		est save "$tables\\`g'_wb_aid_1" , replace

		capture reghdfe `g' l1.lnaid, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year i.ID_adm1_num)
		est save "$tables\\`g'_wb_aid_2" , replace

		capture reghdfe `g' l2.lnaid_c, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year)
		est save "$tables\\`g'_ch_aid_1" , replace

		capture reghdfe `g' l2.lnaid_c, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year i.ID_adm1_num)
		est save "$tables\\`g'_ch_aid_2" , replace
	}
}


********* Initialize empty (.) matrixes with 5 rows and 4 columns (and a 2x8 as appendix)
local panelA_long q7b q4b	q8a	q8b	q8c	q8d
mat B = J(`=wordcount("`panelA_long'")',4,.)
mat SE = B
mat Append = J(2,4,.)

***** Initialize rowcount 
local rowcount = 0
** loop
foreach g in `panelA_long' {
	local ++rowcount

	** WB, Model 1
	est use "$tables\\`g'_wb_aid_1"
	** Extract values
	mat B[`rowcount',1] = _b[l1.lnaid]
	mat SE[`rowcount',1] = _se[l1.lnaid]

	** WB, Model 2
	est use "$tables\\`g'_wb_aid_2"
	** Extract values
	mat B[`rowcount',2] = _b[l1.lnaid]
	mat SE[`rowcount',2] = _se[l1.lnaid]

	** China, Model 1
	est use "$tables\\`g'_ch_aid_1"
	** Extract values
	mat B[`rowcount',3] = _b[l2.lnaid_c]
	mat SE[`rowcount',3] = _se[l2.lnaid_c]

	** China, Model 2
	est use "$tables\\`g'_ch_aid_2"
	** Extract values
	mat B[`rowcount',4] = _b[l2.lnaid_c]
	mat SE[`rowcount',4] = _se[l2.lnaid_c]

}

write_mats B SE using "$tables/panelA_long_a.tex", ///
names(`" "Your living conditions in 12 months time?" "Your own present living conditions?" "Hardship: Gone without food" "Hardship: Gone without water" "Hardship: Gone without healthcare" "Hardship: Gone without electricity" "') ///
ndecimals(3)  stars(B SE)




* Panel B: Security
local panelB_long ea_fac_c ea_sec_a	ea_sec_b	q11a_x	q11b_x 
quietly{
	eststo clear
	foreach g in `panelB_long'{
		capture reghdfe `g' l1.lnaid, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year)
		est save "$tables\\`g'_wb_aid_1" , replace

		capture reghdfe `g' l1.lnaid, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year i.ID_adm1_num)
		est save "$tables\\`g'_wb_aid_2" , replace

		capture reghdfe `g' l2.lnaid_c, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year)
		est save "$tables\\`g'_ch_aid_1" , replace

		capture reghdfe `g' l2.lnaid_c, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year i.ID_adm1_num)
		est save "$tables\\`g'_ch_aid_2" , replace
	}
}


********* Initialize empty (.) matrixes with 5 rows and 4 columns (and a 2x8 as appendix)

local panelB_long ea_fac_c ea_sec_a	ea_sec_b	q11a_x	q11b_x
mat B = J(`=wordcount("`panelB_long'")',4,.)
mat SE = B
mat Append = J(2,4,.)

***** Initialize rowcount 
local rowcount = 0
** loop
foreach g in `panelB_long' {
	local ++rowcount

	** WB, Model 1
	est use "$tables\\`g'_wb_aid_1"
	** Extract values
	mat B[`rowcount',1] = _b[l1.lnaid]
	mat SE[`rowcount',1] = _se[l1.lnaid]

	** WB, Model 2
	est use "$tables\\`g'_wb_aid_2"
	** Extract values
	mat B[`rowcount',2] = _b[l1.lnaid]
	mat SE[`rowcount',2] = _se[l1.lnaid]

	** China, Model 1
	est use "$tables\\`g'_ch_aid_1"
	** Extract values
	mat B[`rowcount',3] = _b[l2.lnaid_c]
	mat SE[`rowcount',3] = _se[l2.lnaid_c]

	** China, Model 2
	est use "$tables\\`g'_ch_aid_2"
	** Extract values
	mat B[`rowcount',4] = _b[l2.lnaid_c]
	mat SE[`rowcount',4] = _se[l2.lnaid_c]

}

write_mats B SE using "$tables/panelB_long_a.tex", ///
names(`" "Security facilities: Police station present within walking distance?" "Security forces: Any policemen or police vehicles?" "Security forces: Any soldiers or army vehicles?" "Frequency of things stolen in past year?" "Frequency of phsysical attacks in the past year?" "') ///
ndecimals(3)  stars(B SE)

* Panel C: Trust in institutions/actors
local panelC_long 	 q40	q22_x	q28a	q28b	q28c	q16_x
quietly{
	eststo clear
	foreach g in `panelC_long'{
		capture reghdfe `g' l1.lnaid, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year)
		est save "$tables\\`g'_wb_aid_1" , replace

		capture reghdfe `g' l1.lnaid, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year i.ID_adm1_num)
		est save "$tables\\`g'_wb_aid_2" , replace

		capture reghdfe `g' l2.lnaid_c, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year)
		est save "$tables\\`g'_ch_aid_1" , replace

		capture reghdfe `g' l2.lnaid_c, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year i.ID_adm1_num)
		est save "$tables\\`g'_ch_aid_2" , replace
	}
}


********* Initialize empty (.) matrixes with 5 rows and 4 columns (and a 2x8 as appendix)

local panelC_long q40	q22_x	q28a	q28b	q28c	q16_x
mat B = J(`=wordcount("`panelC_long'")',4,.)
mat SE = B
mat Append = J(2,4,.)

***** Initialize rowcount 
local rowcount = 0
** loop
foreach g in `panelC_long' {
	local ++rowcount

	** WB, Model 1
	est use "$tables\\`g'_wb_aid_1"
	** Extract values
	mat B[`rowcount',1] = _b[l1.lnaid]
	mat SE[`rowcount',1] = _se[l1.lnaid]

	** WB, Model 2
	est use "$tables\\`g'_wb_aid_2"
	** Extract values
	mat B[`rowcount',2] = _b[l1.lnaid]
	mat SE[`rowcount',2] = _se[l1.lnaid]

	** China, Model 1
	est use "$tables\\`g'_ch_aid_1"
	** Extract values
	mat B[`rowcount',3] = _b[l2.lnaid_c]
	mat SE[`rowcount',3] = _se[l2.lnaid_c]

	** China, Model 2
	est use "$tables\\`g'_ch_aid_2"
	** Extract values
	mat B[`rowcount',4] = _b[l2.lnaid_c]
	mat SE[`rowcount',4] = _se[l2.lnaid_c]

}

write_mats B SE using "$tables/panelC_long_a.tex", ///
names(`" " Democracy: How democratic is your country today?" "Democracy: Did you perceive last elections as free and fair?" "Governance: Reject one-party rule" "Governance: Reject military rule" "Governance: Reject one-man rule" "Reject government banning organizations that go against its policies"  "') ///
ndecimals(3)  stars(B SE)	

* Panel D: Democratic norms and attitudes
local panelD_long q24c_x	q49_x		q51a_x	q42b q27a

eststo clear
foreach g in `panelD_long'{
	capture reghdfe `g' l1.lnaid, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year)
	capture est save "$tables\\`g'_wb_aid_1" , replace

	capture reghdfe `g' l1.lnaid, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year i.ID_adm1_num)
	capture est save "$tables\\`g'_wb_aid_2" , replace

	capture reghdfe `g' l2.lnaid_c, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year)
	capture est save "$tables\\`g'_ch_aid_1" , replace

	capture reghdfe `g' l2.lnaid_c, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year i.ID_adm1_num)
	capture est save "$tables\\`g'_ch_aid_2" , replace
}



********* Initialize empty (.) matrixes with 5 rows and 4 columns (and a 2x8 as appendix)

local panelD_long q24c_x	q49_x		q51a_x	q42b q27a
mat B = J(`=wordcount("`panelD_long'")',4,.)
mat SE = B
mat Append = J(2,4,.)

***** Initialize rowcount 
local rowcount = 0
** loop
foreach g in `panelD_long' {
	local ++rowcount

	** WB, Model 1
	capture{
		est use "$tables\\`g'_wb_aid_1"
		** Extract values
		mat B[`rowcount',1] = _b[l1.lnaid]
		mat SE[`rowcount',1] = _se[l1.lnaid]
	}
	** WB, Model 2
	capture{
		est use "$tables\\`g'_wb_aid_2"
		** Extract values
		mat B[`rowcount',2] = _b[l1.lnaid]
		mat SE[`rowcount',2] = _se[l1.lnaid]
	}
	** China, Model 1
	capture{
		est use "$tables\\`g'_ch_aid_1"
		** Extract values
		mat B[`rowcount',3] = _b[l2.lnaid_c]
		mat SE[`rowcount',3] = _se[l2.lnaid_c]
	}
	** China, Model 2
	capture{
		est use "$tables\\`g'_ch_aid_2"
		** Extract values
		mat B[`rowcount',4] = _b[l2.lnaid_c]
		mat SE[`rowcount',4] = _se[l2.lnaid_c]
	}
}

write_mats B SE using "$tables/panelD_long_a.tex", ///
names(`" "Frequency of contact to government official to express your view" "Fear of political intimidation or violence during campaigns"  "How often do people have to be careful about what they say in politics?" "Rule of Law: People must obey the law"   "Frequency of joining others to request government action"   "') ///
ndecimals(3) 	stars(B SE)



**************************************** Coefficient Plots *****************************************************************

cap drop std_lnaid std_lnaid_c
egen std_lnaid=std(lnaid), mean(0)  std(1)
egen std_lnaid_c=std(lnaid_c), mean(0)  std(1)

global wblag1 			"l1.std_lnaid"
global chinalag2		"l2.std_lnaid_c"

matrix drop _all


// World Bank
* Model 1 - state and year FE
mat B=J(15,2,0)

local no = 1
local short ea_fac_c	ea_sec_a	ea_sec_b	q11a_x	q11b_x			q40	q22_x	q28a	q28b	q28c	q16_x			q24c_x	q49_x		q51a_x	q42b 

eststo clear
foreach g in `short'{
	capture reghdfe `g' $wblag1, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year)

	capture scalar b`no' = _b[$wblag1]
	capture scalar s`no' = _se[$wblag1]
	capture matrix B[`no', 1] =  b`no'
	capture matrix B[`no', 2] =  s`no'
	local no = `no'+1
}

*Model 2 - state, year and region FE
mat C=J(15,2,0)
local no = 1
local short ea_fac_c	ea_sec_a	ea_sec_b	q11a_x	q11b_x			q40	q22_x	q28a	q28b	q28c	q16_x			q24c_x	q49_x		q51a_x	q42b 
eststo clear
foreach g in `short'{
	capture reghdfe `g' $wblag1, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$wblag1]					
	capture scalar s`no' = _se[$wblag1]				
	capture matrix C[`no', 1] =  b`no'				
	capture matrix C[`no', 2] =  s`no'				
	local no = `no'+1							
}

// China
* Model 1 - state and year FE
mat D=J(15,2,0)	

local no = 1
local short ea_fac_c	ea_sec_a	ea_sec_b	q11a_x	q11b_x			q40	q22_x	q28a	q28b	q28c	q16_x			q24c_x	q49_x		q51a_x	q42b 
eststo clear
foreach g in `short'{
	capture reghdfe `g' $chinalag2, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year)

	capture scalar b`no' = _b[$chinalag2]
	capture scalar s`no' = _se[$chinalag2]
	capture matrix D[`no', 1] =  b`no'
	capture matrix D[`no', 2] =  s`no'
	local no = `no'+1
}

* Model 2 - state, year and region FE
mat E=J(15,2,0)
local no = 1
local short ea_fac_c	ea_sec_a	ea_sec_b	q11a_x	q11b_x			q40	q22_x	q28a	q28b	q28c	q16_x			q24c_x	q49_x		q51a_x	q42b 
eststo clear
foreach g in `short'{
	capture reghdfe `g' $chinalag2, cluster(i.state#i.transaction_year i.ID_adm1_num) absorb(i.state i.transaction_year i.ID_adm1_num)
	capture scalar b`no' = _b[$chinalag2]					
	capture scalar s`no' = _se[$chinalag2]				
	capture matrix E[`no', 1] =  b`no'				
	capture matrix E[`no', 2] =  s`no'				
	local no = `no'+1							
}


graph set window fontface stSans



coefplot (matrix(B[,1]), se(B[,2]) mcolor("58 85 164") msymbol(o) ciopts(lcolor("58 85 164") lwidth(thin) recast(rcap))  ) (matrix(C[,1]), se(C[,2]) mcolor("58 85 164") msymbol(oh) ciopts(lcolor("58 85 164") lwidth(thin) recast(rcap)) ) 	  , ///
graphregion(color(white))  xline(0, lcolor(grey) lwidth(vthin) ) grid(none)  /// 
coeflabels(r1="Security facilities: Police station present within walking distance? " ///
	r2="Security forces: Any policemen or police vehicles?" /// 
	r3="Security forces: Any soldiers or army vehicles?"  /// 
	r4="Frequency of things stolen in the past year?" ///
	r5="Frequency of physically attacks in the past year?"  /// 
	r6=" Democracy: How democratic is your country today?"  ///
	r7="Democracy: Did you perceive last elections as free and fair?"  /// 
	r8="Governance: Reject one-party rule" /// 
	r9="Governance: Reject military rule"  /// 
	r10="Governance: Reject one-man rule"  ///
	r11="Reject government ban of organizations that go against its policies"   ///
	r12="Frequency of contact to government official to express your view" /// 
	r13="Fear of political intimidation or violence during campaigns" ///
	r14="How often people have to be careful about what to say in politics?" /// 
	r15="Rule of Law: People must obey the law"   /// 
	r16= "Frequency of joining others to request government action", labsize(small))  ///
xlabel( , labsize(small))   levels(90)  fxsize(178)  ///
headings(r1 = "{bf:Panel A: Security}"                     ///
	r6 = "{bf:Panel B: Democratic norms and attitudes}"                        ///
	r12 = "{bf: Panel C: Government responsiveness and repression }") ///
title("WB", size(small)) xscale(range(-0.2(0.1)0.2)) xlabel(-0.2(0.1)0.2) ///
legend(on order(2 "State and year fixed effects" 4 "State, year and region fixed effects") size(vsmall) col(1) )
graph save wb.gph, replace

//			    legend(label(2 "State and year fixed effects")   label(4 "State, year and region fixed effects") size(tiny) col(1) )



coefplot (matrix(D[,1]), se(D[,2]) mcolor("212 82 154") msymbol(o) ciopts(lcolor("212 82 154") lwidth(thin) recast(rcap))  ) (matrix(E[,1]), se(E[,2]) mcolor("212 82 154") msymbol(oh) ciopts(lcolor("212 82 154") lwidth(thin) recast(rcap)) ) , ///
graphregion(color(white))  xline(0, lcolor(grey) lwidth(vthin) ) grid(none)  ///
xlabel( , labsize(small))  nolabels ylabel(,nolabel)  levels(90)  fxsize(68)  /// 
headings(r1 = " "                     ///
	r6 = " "                        ///
	r12 = " ") ///
title("China", size(small)) xscale(range(-0.2(0.1)0.2)) xlabel(-0.2(0.1)0.2)  ///
legend(on order(2 "State and year FE" 4 "State, year and region FE") size(vsmall) col(1) )

graph save china.gph, replace
graph combine wb.gph china.gph  , graphregion(color(white))
graph export "$graphs/coefplot_final.png", as(png) replace 
graph export "$graphs/coefplot_final.eps", replace 	
graph export "$graphs/coefplot_final.pdf", replace 	

* Melvin Wog opened wb.gph and china.gph manually in STATA's graph editor, changed the font and save the graphs. The two command lines below combine these new graphs	
graph combine wb_sansserif.gph china_sansserif.gph  , graphregion(color(white))
graph export "$graphs/coefplot_final_sf.png", as(png) replace 
graph export "$graphs/coefplot_final_sf.eps", replace 	
// note: the quality of the png is very bad when the code is executed. Melvin Wong opened the graph editor and saved the graph as pdf, which has much better quality and a small file size 


graph set window fontface default

